package com.sbs.gaoxinqutoilet.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.ListPopupWindow;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.lvfq.pickerview.TimePickerView;
import com.sbs.gaoxinqutoilet.R;
import com.sbs.gaoxinqutoilet.adapter.CeFangAdapter;
import com.sbs.gaoxinqutoilet.adapter.GaizaoTypeAdapter;
import com.sbs.gaoxinqutoilet.base.BaseBackFragment;
import com.sbs.gaoxinqutoilet.entity.AddNewBuildTypeEntity;
import com.sbs.gaoxinqutoilet.entity.AddNewInfoImageEntity;
import com.sbs.gaoxinqutoilet.entity.AddNewShiGongTeamEntity;
import com.sbs.gaoxinqutoilet.entity.CountyEntity;
import com.sbs.gaoxinqutoilet.entity.FIleEditSaveUpEntity;
import com.sbs.gaoxinqutoilet.entity.MenPaiHaoEntity;
import com.sbs.gaoxinqutoilet.entity.MessageEvent;
import com.sbs.gaoxinqutoilet.entity.UploadImageEntity;
import com.sbs.gaoxinqutoilet.entity.UserEntity;
import com.sbs.gaoxinqutoilet.eventbus.EventCenter;
import com.sbs.gaoxinqutoilet.http.HttpApis;
import com.sbs.gaoxinqutoilet.http.Request;
import com.sbs.gaoxinqutoilet.interfaces.AddNewShigTeamPopuListener;
import com.sbs.gaoxinqutoilet.interfaces.BuildTypePopuListener;
import com.sbs.gaoxinqutoilet.interfaces.CeFangPopuListener;
import com.sbs.gaoxinqutoilet.interfaces.Constants;
import com.sbs.gaoxinqutoilet.interfaces.ContyPopuListener;
import com.sbs.gaoxinqutoilet.interfaces.DialogClick;
import com.sbs.gaoxinqutoilet.interfaces.EventConstant;
import com.sbs.gaoxinqutoilet.interfaces.PopuClickListener;
import com.sbs.gaoxinqutoilet.myapp.MyApplication;
import com.sbs.gaoxinqutoilet.utils.GsonTools;
import com.sbs.gaoxinqutoilet.utils.HttpUtils;
import com.sbs.gaoxinqutoilet.utils.ImageUtils;
import com.sbs.gaoxinqutoilet.utils.JsonUtil;
import com.sbs.gaoxinqutoilet.utils.LogUtils;
import com.sbs.gaoxinqutoilet.utils.NetTimeUtils;
import com.sbs.gaoxinqutoilet.utils.RegexUtils;
import com.sbs.gaoxinqutoilet.utils.SPUtil;
import com.sbs.gaoxinqutoilet.utils.StringUtil;
import com.sbs.gaoxinqutoilet.utils.appinstallerutils.ConvertUtils;
import com.sbs.gaoxinqutoilet.view.JeScroolView;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.iwf.photopicker.PhotoPicker;
import top.zibin.luban.Luban;

/**
 * Created by 聪明一只哈 on 2018/6/14.
 * Time: 2018/6/14  18:39
 */

public class AddNewFileFragment extends BaseBackFragment {

    @BindView(R.id.toolbar_back)
    ImageView toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_iv_menu)
    ImageView toolbarIvMenu;
    @BindView(R.id.toolbar_tv_menu)
    TextView toolbarTvMenu;
    @BindView(R.id.toolbar_rl_menu)
    AutoRelativeLayout toolbarRlMenu;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.add_new_file_header)
    View addNewFileHeader;
    @BindView(R.id.add_new_et_address_village)
    TextView addNewEtAddress_village;
    @BindView(R.id.add_new_acceptance_address)
    AutoLinearLayout addNewAcceptanceAddress;
    @BindView(R.id.add_new_et_doorcode)
    EditText addNewEtDoorcode;
    @BindView(R.id.add_new_acceptance_doorcode)
    AutoLinearLayout addNewAcceptanceDoorcode;
    @BindView(R.id.add_new_et_doorname)
    EditText addNewEtDoorname;
    @BindView(R.id.add_new_et_humans)
    EditText addNewEtHumans;
    @BindView(R.id.add_new_et_tel)
    EditText addNewEtTel;
    @BindView(R.id.add_new_acceptance_doorname)
    AutoLinearLayout addNewAcceptanceDoorname;
    @BindView(R.id.add_new_et_doornumberning)
    TextView addNewEtDoornumberning;
    @BindView(R.id.add_new_acceptance_doornumbering)
    AutoLinearLayout addNewAcceptanceDoornumbering;
    @BindView(R.id.add_new_et_idnumber)
    EditText addNewEtIdnumber;
    @BindView(R.id.add_new_acceptance_idnumber)
    AutoLinearLayout addNewAcceptanceIdnumber;
    @BindView(R.id.v_line_file)
    View vLineFile;
    @BindView(R.id.add_new_tv_isIdel)
    TextView addNewTvIsIdel;
    @BindView(R.id.add_new_et_address_conty)
    TextView add_newaddress_Contry;
    @BindView(R.id.add_new_et_address_town)
    TextView add_newaddress_Town;
    @BindView(R.id.add_new_acceptance_isIdel)
    AutoLinearLayout addNewAcceptanceIsIdel;
    @BindView(R.id.add_new_tv_buildstate)
    TextView addNewTvBuildstate;
    @BindView(R.id.add_new_acceptance_buildstate)
    AutoLinearLayout addNewAcceptanceBuildstate;
    @BindView(R.id.add_new_tv_buildtype)
    TextView addNewTvBuildtype;
    @BindView(R.id.add_new_acceptance_buildtype)
    AutoLinearLayout addNewAcceptanceBuildtype;
    @BindView(R.id.add_new_tv_teamname)
    TextView addNewTvTeamname;
    @BindView(R.id.add_new_acceptance_teamname)
    AutoLinearLayout addNewAcceptanceTeamname;
    @BindView(R.id.add_new_tv_huafeichi)
    TextView addNewTvHuafeichi;


    @BindView(R.id.add_new_tv_bianchi)
    TextView addNewTvBianchi;
    @BindView(R.id.add_new_tv_chongshui)
    TextView addNewTvChongshui;
    @BindView(R.id.add_new_tv_cefang)
    TextView addNewTvCefang;
    @BindView(R.id.add_new_tv_dengjiren)
    TextView addNewTvDengjiren;
    @BindView(R.id.add_new_tv_caozuotime)
    TextView addNewTvCaozuotime;
    @BindView(R.id.addnew_tv_buildyear)
    TextView addNewTvBuildyear;
    @BindView(R.id.add_new_tv_buildStyle)
    TextView addNewTvBuildStyle;


    @BindView(R.id.all_acceptance_huafeichi)
    AutoLinearLayout allAcceptanceHuafeichi;
    @BindView(R.id.sell_iv_myFile_three)
    ImageView sellIvMyFileThree;
    @BindView(R.id.up_all_before)
    AutoRelativeLayout upAllBefore;
    @BindView(R.id.sell_iv_myFile_four)
    ImageView sellIvMyFileFour;
    @BindView(R.id.up_all_ing)
    AutoRelativeLayout upAllIng;
    @BindView(R.id.sell_iv_myFile_five)
    ImageView sellIvMyFileFive;
    @BindView(R.id.up_all_after)
    AutoRelativeLayout upAllAfter;
    @BindView(R.id.sell_iv_myFile_one)
    ImageView sellIvMyFileOne;
    @BindView(R.id.up_all_idpic)
    AutoRelativeLayout upAllIdpic;
    @BindView(R.id.sell_iv_myFile_two)
    ImageView sellIvMyFileTwo;
    @BindView(R.id.up_all_frontdoor)
    AutoRelativeLayout upAllFrontdoor;
    @BindView(R.id.arl_temp)
    AutoRelativeLayout arlTemp;
    @BindView(R.id.add_new_bt_save)
    Button addNewBtSave;
    @BindView(R.id.add_new_arl_click_state)
    AutoRelativeLayout addNewArlClickState;
    @BindView(R.id.add_jescrollview)
    JeScroolView addJescrollview;
    @BindView(R.id.image_show_b)
    ImageView image_show_B;
    @BindView(R.id.image_show_m)
    ImageView image_show_M;
    @BindView(R.id.image_show_f)
    ImageView image_show_F;
    @BindView(R.id.image_show_id)
    ImageView image_show_ID;
    @BindView(R.id.image_show_d)
    ImageView image_show_D;
    @BindView(R.id.toolbar_iv_add)
    ImageView toolbarIvAdd;
    @BindView(R.id.add_new_acceptance_humans)
    AutoLinearLayout addNewAcceptanceHumans;
    @BindView(R.id.add_new_acceptance_tel)
    AutoLinearLayout addNewAcceptanceTel;
    @BindView(R.id.all_acceptance_bianchi)
    AutoLinearLayout allAcceptanceBianchi;
    @BindView(R.id.all_acceptance_chongshui)
    AutoLinearLayout allAcceptanceChongshui;
    @BindView(R.id.all_acceptance_cefang)
    AutoLinearLayout allAcceptanceCefang;
    @BindView(R.id.all_acceptance_dengjiren)
    AutoLinearLayout allAcceptanceDengjiren;
    @BindView(R.id.all_acceptance_caozuotime)
    AutoLinearLayout allAcceptanceCaozuotime;
    @BindView(R.id.image_gaizaozhongtwo)
    ImageView imageGaizaozhongtwo;
    @BindView(R.id.sell_iv_gaizaozhongtwo)
    ImageView sellIvGaizaozhongtwo;
    @BindView(R.id.up_all_gaizaozhongtwo)
    AutoRelativeLayout upAllGaizaozhongtwo;
    @BindView(R.id.image_gaizaozhongthree)
    ImageView imageGaizaozhongthree;
    @BindView(R.id.sell_iv_gaizaozhongthree)
    ImageView sellIvGaizaozhongthree;
    @BindView(R.id.up_all_gaizaozhongthree)
    AutoRelativeLayout upAllGaizaozhongthree;
    @BindView(R.id.view_ll1)
    AutoRelativeLayout view_ll1;
    @BindView(R.id.view_ll2)
    AutoRelativeLayout view_ll2;
    Unbinder unbinder;


    private File mCurrentPhotoFile;
    private ListPopupWindow contyPopupWindow;

    //图片名称除重
    private List<String> imageName=new ArrayList<>();

    //乡级列表
    private List<CountyEntity> contylist = new ArrayList<>();
    //县级列表
    private List<CountyEntity> twonlist = new ArrayList<>();
    //村级列表
    private List<CountyEntity> villagelist = new ArrayList<>();
    //获取县乡村的name
    private List<String> namelist = new ArrayList<>();
    //是否闲置
    private List<String> isIdleList = new ArrayList<>();
    //改造状态
    private List<String> stateList = new ArrayList<>();
    //改造年份
    private List<String> buildyearList = new ArrayList<>();
    //改厕方式
    private List<String> buildStyleList = new ArrayList<>();
    private ContyRequest cavRequest;
    private TwonRequest twonRequest;
    private VillageRequest villageRequest;
    private ListPopupWindow twonPopupWindow;
    private ListPopupWindow villagePopupWindow;
    private ListPopupWindow isIdlePopupWindow;
    private ListPopupWindow buildstatePopupWindow;
    private ListPopupWindow addnewbtypePopupWindow;
    private List<AddNewBuildTypeEntity> addNewBuildTypeEntityList;
    private List<AddNewShiGongTeamEntity> huafenchiEntityList;
    private List<AddNewShiGongTeamEntity> bainchiEntityList;
    private List<AddNewShiGongTeamEntity> shuichongEntityList;
    private List<AddNewShiGongTeamEntity> ceFangEntityList;
    private ListPopupWindow addnewshigongteamPopupWindow;
    private List<AddNewShiGongTeamEntity> addNewShigongteamEntityList;
    //拼接参数的集合
    private Map<String, String> saveparams = new TreeMap<>();
    //临时状态
    private boolean isUploadSuccess;
    //5张图片是否上传成功的状态


    private boolean isImageIdSuccess;//身份证照片
    private boolean isImageDoorFontSuccess;//大门前照片
    private boolean isImageBfSuccess;//改造前照片
    private boolean isImageMidSuccess;//改造中照片
    private boolean isImageAfSuccess;//改造后照片
    private boolean isImageMidTwoSuccess;//改造后照片
    private boolean isImageMidThreeSuccess;//改造后照片



    private ListPopupWindow huafenchiPopupWindow;
    private ListPopupWindow chongshuiPopupWindow;
    private ListPopupWindow cefangPopupWindow;
    private CeFangAdapter myAdapter;
    private ListPopupWindow addnew_buildyear;
    private TimePickerView caozuoTime;
    private String netTime;
    private ListPopupWindow addnew_buildStyle;
    private String token_data;
    private GaizaoTypeAdapter myBuildTypeAdapter;

    public static AddNewFileFragment newInstance() {
        Bundle args = new Bundle();
        AddNewFileFragment fragment = new AddNewFileFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_addnew, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView(inflater);
        initData();
        return attachToSwipeBack(view);
    }


    /**
     * 初始化view
     *
     * @param inflater
     */
    private void initView(LayoutInflater inflater) {
        EventBus.getDefault().register(this);

        imageName.clear();

        token_data = SPUtil.getString(Constants.KEY_TOKEN, "");
        toolbarTitle.setText("户厕新增");
        //返回按钮
        toolbarBack.setVisibility(View.VISIBLE);
        //设置回键
        initToolbarBack(toolbar);
        //showAlertOnlyPos(_mActivity,"户厕新增","请先选择辖区单位");

        getNetTimeNow();
    }

    private void getNetTimeNow() {
        new Thread() {
            @Override
            public void run() {
                netTime = NetTimeUtils.getNetTime();
            }
        }.start();
    }
    /**
     * 获取初始化数据
     */
    private void initData() {
        //=============================
        isIdleList.add("是");
        isIdleList.add("否");
        //=============================
        stateList.add("改造中");
        stateList.add("已改造");
        stateList.add("未改造");
        stateList.add("旧有改造");
        //=============================
        //限制信息默认 否
        addNewTvIsIdel.setText("否");
        //==============================
        //改造年份

        buildyearList.add("2020年之前");
        buildyearList.add("2020年");

        //==============================
        //改厕方式
        buildStyleList.add("农户自改自建");
        buildStyleList.add("政府主导统一施工");


        //==============================
        //获取个人信息
        UserEntity userEntity = SPUtil.getBeanValue(Constants.KEY_USER, UserEntity.class);
        if (userEntity != null) {
            //获取乡级列表
            getContyList(userEntity);
            getTownList("130171000000");
        }

    }


    /**
     * 获取乡级列表
     *
     * @param userEntity
     */
    private void getContyList(UserEntity userEntity) {
        //需要拼接
        // String addnew_url = HttpApis.addnew_info+userEntity.getArea_id()+"/"+userEntity.getArea_level();
        String addnew_url = HttpApis.addnew_info + userEntity.getArea_id() + "/" + "3";
        showLoadingDialog("正在加载县级数据");
        if (cavRequest == null) {
            cavRequest = new ContyRequest();
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);
        Log.i("乡级列表", "url: " + addnew_url);
        HttpUtils.requestGet(_mActivity, addnew_url,map, cavRequest);
    }

    /**
     * 获取县级列表
     *
     * @param conty_id
     */
    private void getTownList(String conty_id) {
        String addnew_url = HttpApis.addnew_info + conty_id + "/" + "4";
        if (twonRequest == null) {
            twonRequest = new TwonRequest();
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);
        Log.i("县级列表", "url: " + addnew_url);
        HttpUtils.requestGet(_mActivity, addnew_url,map, twonRequest);
    }

    /**
     * 获取村级列表
     *
     * @param teon_id
     */
    private void getVillageList(String teon_id) {
        String addnew_url = HttpApis.addnew_info + teon_id + "/" + "5";
        if (villageRequest == null) {
            villageRequest = new VillageRequest();
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);
        Log.i("村级列表", "url: " + addnew_url);
        HttpUtils.requestGet(_mActivity, addnew_url,map, villageRequest);
    }
    private class ContyRequest extends Request {
        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);
            Log.i("乡级列表", "success: " + jsonStr);
            Type type = new TypeToken<ArrayList<CountyEntity>>() {
            }.getType();
            contylist = JsonUtil.json2Collection(jsonStr, type);
            cancelLoadingDialog();
        }

        @Override
        public void error(String error) {
            super.error(error);
            Log.i("乡级列表", "error: " + error);
            cancelLoadingDialog();
        }
    }

    private class TwonRequest extends Request {
        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);
            Log.i("县级列表", "success: " + jsonStr);
            Type type = new TypeToken<ArrayList<CountyEntity>>() {
            }.getType();
            twonlist = JsonUtil.json2Collection(jsonStr, type);
            cancelLoadingDialog();
        }

        @Override
        public void error(String error) {
            super.error(error);
            Log.i("县级列表", "error: " + error);
            cancelLoadingDialog();
        }
    }

    private class VillageRequest extends Request {
        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);
            Log.i("村级列表", "success: " + jsonStr);
            Type type = new TypeToken<ArrayList<CountyEntity>>() {
            }.getType();
            villagelist = JsonUtil.json2Collection(jsonStr, type);
            cancelLoadingDialog();
        }
        @Override
        public void error(String error) {
            super.error(error);
            Log.i("村级列表", "error: " + error);
            cancelLoadingDialog();
        }
    }


    /**
     * eventbus 页面跳转,事件接受
     *
     * @param center
     */
    @Subscribe
    public void onEventReceive(EventCenter center) {

        if (center.getEventCode() == EventConstant.UPLOAD_BUY_MODIFY) {

        }
    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        //获取权限
        showPermission();
    }

    private AddNewInfoImageEntity addnewentity = new AddNewInfoImageEntity();
    private String[] before_ima = new String[]{null, null, null, null, null, null, null, null};
    private String[] ing_ima = new String[]{null, null, null, null, null, null, null, null};
    private String[] after_ima = new String[]{null, null, null, null, null, null, null, null};
    private String[] idcard_ima = new String[]{null, null, null, null, null, null, null, null};
    private String[] fodoor_ima = new String[]{null, null, null, null, null, null, null, null};
    private String[] ing_two_ima = new String[]{null, null, null, null, null, null, null, null};
    private String[] ing_three_ima = new String[]{null, null, null, null, null, null, null, null};

    @OnClick({R.id.add_new_et_address_town, R.id.add_new_et_address_conty,
            R.id.add_new_et_address_village, R.id.add_new_tv_isIdel,
            R.id.add_new_tv_buildstate, R.id.add_new_tv_buildtype,
            R.id.add_new_tv_teamname, R.id.up_all_before, R.id.up_all_ing,
            R.id.up_all_after, R.id.up_all_idpic, R.id.up_all_frontdoor,
            R.id.add_new_bt_save, R.id.all_acceptance_huafeichi,
            R.id.add_new_tv_huafeichi, R.id.add_new_tv_bianchi,
            R.id.add_new_tv_chongshui, R.id.add_new_tv_cefang,
            R.id.add_new_et_doornumberning, R.id.add_new_tv_dengjiren,
            R.id.add_new_tv_caozuotime, R.id.up_all_gaizaozhongtwo,
            R.id.up_all_gaizaozhongthree,R.id.addnew_tv_buildyear,
            R.id.add_new_tv_buildStyle})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //选择县
            case R.id.add_new_et_address_conty:
                contyPopupWindow = new ListPopupWindow(_mActivity);
                setPopuData(view, contyPopupWindow, contylist);
                setPopuClickListener(new ContyPopuListener() {
                    @Override
                    public void show(CountyEntity Centity, String text) {
                        add_newaddress_Contry.setText(Centity.getText());
                        showLoadingDialog("正在加载乡镇数据");
                        //addNewBtSave.setBackgroundResource(R.drawable.toilet_sliding_tv_selected);
                        getTownList(Centity.getValue());

                    }
                });
                break;
            //乡(镇)
            case R.id.add_new_et_address_town:
                String conty_address = add_newaddress_Contry.getText().toString().trim();
                if (TextUtils.isEmpty(conty_address) || "县".equals(conty_address)) {
                    showShortToast("请先选择县级单位");
                    return;
                } else {
                    try {
                        if (twonlist != null && twonlist.size() > 0) {
                            twonPopupWindow = new ListPopupWindow(_mActivity);
                            setPopuData(view, twonPopupWindow, twonlist);
                            setPopuClickListener(new ContyPopuListener() {
                                @Override
                                public void show(CountyEntity Centity, String text) {
                                    //施工队会根据村级列表的条目的id来查询,用sp存储
                                    SPUtil.putString(Constants.ADDNEWVV, Centity.getValue());
                                    add_newaddress_Town.setText(Centity.getText());
                                    showLoadingDialog("正在加载村级数据");
                                    getVillageList(Centity.getValue());
                                }
                            });
                        }
                    } catch (Exception e) {
                        Log.i("list为null", "乡级列表onViewClicked: " + e.toString());
                    }
                }
                break;
            //选择村
            case R.id.add_new_et_address_village:
                String town_address = add_newaddress_Town.getText().toString().trim();
                if (TextUtils.isEmpty(town_address) || "乡(镇)".equals(town_address)) {
                    showShortToast("请先选择乡级单位");
                    return;
                } else {

                    try {
                        if (villagelist != null && villagelist.size() > 0) {
                            villagePopupWindow = new ListPopupWindow(_mActivity);
                            setPopuData(view, villagePopupWindow, villagelist);
                            setPopuClickListener(new ContyPopuListener() {
                                @Override
                                public void show(CountyEntity Centity, String text) {
                                    addNewEtAddress_village.setText(Centity.getText());
                                    // TODO: 2018/6/19 设置参数
                                    //辖区单位对应的id
                                    //换成bean类
                                    // saveparams.put("area_id", Centity.getValue());
                                    //施工队会根据村级列表的条目的id来查询,用sp存储
                                    //SPUtil.putString(Constants.ADDNEWVV, Centity.getValue());
                                    SPUtil.putString(Constants.MENPAIHAO, Centity.getValue());
                                    addnewentity.setArea_id(Centity.getValue());


                                    //getHubianhaoData(Centity.getValue());

                                }
                            });
                        }
                    } catch (Exception e) {
                        Log.i("list为null", "村级列表onViewClicked: " + e.toString());

                    }
                }


                break;

            case R.id.add_new_et_doornumberning:

                //ToastUtils.showShortToast(_mActivity, "点击选择户编号，跳转到一个页面，选择数据回显");
                //showAlertOnlyPos(_mActivity, "户编号", "点击选择户编号，跳转到一个页面，选择数据回显");

                break;

            //是否闲置
            case R.id.add_new_tv_isIdel:
                //0  否  1  是
                isIdlePopupWindow = new ListPopupWindow(_mActivity);
                setdefaultPopuData(view, isIdlePopupWindow, isIdleList);
                setdefaultPopuClickListener(new PopuClickListener() {
                    @Override
                    public void show(String mess) {
                        addNewTvIsIdel.setText(mess);
                        //添加到参数中

                    }
                });


                break;
            //改造状态
            case R.id.add_new_tv_buildstate:
                buildstatePopupWindow = new ListPopupWindow(_mActivity);
                setdefaultPopuData(view, buildstatePopupWindow, stateList);
                setdefaultPopuClickListener(new PopuClickListener() {
                    @Override
                    public void show(String mess) {
                        addNewTvBuildstate.setText(mess);
                        UpShowForState(mess);
                    }
                });

                //当用户的改造状态为未改造时不需要录入改造类型、施工队名称和化粪池材料，需上传身份证照片、大门照和改造前照片，
                // 当状态为改造中需要选择改造类型、施工队名称、
                // 化粪池材料，上传图片包括身份证、大门照、改造前和改造中。状态为已改造在改造中限制基础上增加需上传改造后照片。

                break;
            //改造年份
            case R.id.addnew_tv_buildyear:
                addnew_buildyear = new ListPopupWindow(_mActivity);
                setdefaultPopuData(view,addnew_buildyear,buildyearList);
                setdefaultPopuClickListener(new PopuClickListener() {
                    @Override
                    public void show(String mess) {
                        addNewTvBuildyear.setText(mess);
                        //stat_year
                        if("2020年之前".equals(mess)){
                            addnewentity.setStat_year("2019");
                        }else if("2020年".equals(mess)){
                            addnewentity.setStat_year("2020");
                        }
                        addnewentity.setStat_year_n(mess);
                    }
                });

                break;

            //改造类型
            case R.id.add_new_tv_buildtype:
                //根据改造状态,请求改造类型
                getStateType(view);


                break;

            //改厕方式
            case R.id.add_new_tv_buildStyle:

                addnew_buildStyle = new ListPopupWindow(_mActivity);
                setdefaultPopuData(view, addnew_buildStyle,buildStyleList);
                setdefaultPopuClickListener(new PopuClickListener() {
                    @Override
                    public void show(String mess) {
                        addNewTvBuildStyle.setText(mess);
                    }
                });


                break;

            //施工队
            case R.id.add_new_tv_teamname:

                String village_data = add_newaddress_Town.getText().toString().trim();
                if (TextUtils.isEmpty(village_data) || "乡(镇)".equals(village_data)) {
                    Toast.makeText(_mActivity, "请选择乡级位置", Toast.LENGTH_SHORT).show();
                    return;
                }

                //这里又改为了乡的id ,不用截取
                String village_value = SPUtil.getString(Constants.ADDNEWVV, "");
                Log.i("施工队", "getShigongTeamData: " + village_value);
                if (!TextUtils.isEmpty(village_value) && village_value != null) {
                    village_value = village_value.substring(0, 9);
                }

                getShigongTeamData(view, village_value);

                break;
            //获取化粪池材料列表数据
            case R.id.add_new_tv_huafeichi:
                getHuaFenChiCailiao(view);
                break;
            //获取便池类型列表数据
            case R.id.add_new_tv_bianchi:
                getBianchiType(view);
                break;
            //获取冲水方式列表数据
            case R.id.add_new_tv_chongshui:
                getShuichongTYpe(view);
                break;
            //获取厕房类型列表数据
            case R.id.add_new_tv_cefang:
                addNewTvCefang.setText("");
                getCeFangType(view);
                break;
            //获取登记人数据
            case R.id.add_new_tv_dengjiren:
                //ToastUtils.showShortToast(_mActivity, "获取登记人数据");

                break;
            //获取最新操作时间
            case R.id.add_new_tv_caozuotime:

                break;

            //5张照片的点击按钮
            case R.id.up_all_before:
                mLayoutType = 1;
                showPhotoPic();
                break;
            case R.id.up_all_ing:
                mLayoutType = 2;
                showPhotoPic();
                break;
            case R.id.up_all_after:
                mLayoutType = 3;
                showPhotoPic();
                break;
            case R.id.up_all_idpic:
                mLayoutType = 4;
                showPhotoPic();
                break;
            case R.id.up_all_frontdoor:
                mLayoutType = 5;
                showPhotoPic();
                break;
            //改造中2 图片
            case R.id.up_all_gaizaozhongtwo:
                mLayoutType = 6;
                showPhotoPic();
                break;
            //改造中3 图片
            case R.id.up_all_gaizaozhongthree:
                mLayoutType = 7;
                showPhotoPic();
                break;
            //提交按钮
            case R.id.add_new_bt_save:
                showLoadingDialog();
                //门牌号 addNewEtDoorcode  不是必填  新增门牌号不验证必填
                final String menpaihao = addNewEtDoorcode.getText().toString().trim();
                addnewentity.setMenpaihao(menpaihao);
                if (!TextUtils.isEmpty(menpaihao)) {//不为空,说明已经填写
                    // 校验  只允许字母、数字和汉字
                    if (RegexUtils.getCheckRegex(menpaihao)) {
                        showShortToast("门牌号不可输入符号");
                        return;
                    } else {
                        String village = SPUtil.getString(Constants.MENPAIHAO, "");
                        final String check_menph = HttpApis.addnew_jiaoyanmenph + menpaihao;

                        final Map<String, String> params = new HashMap<>();
                        params.put("idvalue", village + ":0");
                        params.put("token",token_data);
                        //参数： 'idvalue='+所选村的地区ID+':' +本条记录的主键值（新增时为0）

                        HttpUtils.requestPost(_mActivity, check_menph, params, new Request() {

                            @Override
                            public void success(String jsonStr) {
                                super.success(jsonStr);
                                Log.i("校验门牌号", "getCheckMenPaihao: " + jsonStr);
                                MenPaiHaoEntity menPaiHaoEntity = GsonTools.changeGsonToBean(jsonStr, MenPaiHaoEntity.class);
                                if (menPaiHaoEntity != null) {
                                    if (1 == menPaiHaoEntity.getValid()) {
                                        //showShortToast("门牌号重复,请重新输入");
                                        showAlertOnlyPos(_mActivity,"门牌号","门牌号重复，请重新输入");
                                        cancelLoadingDialog();
                                        return;
                                    } else {
                                        addnewentity.setMenpaihao(menpaihao + "");
                                        cancelLoadingDialog();
                                        BtSave();
                                    }
                                }
                            }

                            @Override
                            public void error(String error) {
                                super.error(error);
                                Log.i("校验门牌号", "getCheckMenPaihao: " + error);
                                cancelLoadingDialog();
                            }
                        });
                    }

                } else {
                    //为空  直接提交数据
                    BtSave();
                }

                break;
        }
    }


    private void BtSave() {
        //检查各个字段的值
        boolean isCheck = CheckFildValue();
        if (!isCheck) {
            cancelLoadingDialog();
            return;
        }

        //addnew_save  上传数据
        AddNewUpFildData();
    }

    /**
     * 获取厕房数据
     *
     * @param view
     */
    private void getCeFangType(final View view) {
        showLoadingDialog("厕房类型...");
        String the_last = HttpApis.addnew_cefang;
        Log.i("厕房类型", "url: " + the_last);
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);
        HttpUtils.requestGet(_mActivity, the_last,map, new Request() {
            @Override
            public void success(String jsonStr) {
                super.success(jsonStr);

                Log.i("厕房类型", "success: " + jsonStr);

                Type type = new TypeToken<ArrayList<AddNewShiGongTeamEntity>>() {
                }.getType();


                ceFangEntityList = JsonUtil.json2Collection(jsonStr, type);

                showCeFangPopu(view);

                cancelLoadingDialog();
            }

            @Override
            public void error(String error) {
                super.error(error);
                Log.i("厕房类型", "error: " + error);

                cancelLoadingDialog();
            }
        });
    }

    /**
     * 加载厕房数据
     *
     * @param view
     */
    private void showCeFangPopu(View view) {

        beanShowList.clear();
        beanList.clear();
        beanIDList.clear();
        cefangPopupWindow = new ListPopupWindow(_mActivity);
        setCeFangPopuData(view, cefangPopupWindow, ceFangEntityList);

        setCeFangPopuClickListener(new CeFangPopuListener() {
            @Override
            public void show(List<AddNewShiGongTeamEntity> datalist) {
//                beanList.clear();
//                //beanIDList.clear();
//                for (AddNewShiGongTeamEntity rb : beanShowList) {
//                    beanList.add(rb.getText());
//                    // beanIDList.add(rb.getValue());
//                }
//                addNewTvCefang.setText("" + beanList.toString());

//                addnewentity.setCefang_n(beanList.toString());
//                addnewentity.setCefang(beanIDList.toString());

                beanList.clear();
                beanIDList.clear();
                for (AddNewShiGongTeamEntity rb : beanShowList) {
                    beanList.add(rb.getText());
                    beanIDList.add(rb.getValue());
                }

                String cefang_n = beanList.toString();// String str2 = str.replaceAll(" ", "");
//                cefang_n = cefang_n.replace("[", "");
//                cefang_n = cefang_n.replace("]", "");
//                cefang_n = cefang_n.replaceAll(" ", "");
                if(cefang_n.contains("[")){
                    cefang_n= StringUtil.deleteCharString(cefang_n,'[');
                }
                if(cefang_n.contains("]")){
                    cefang_n= StringUtil.deleteCharString(cefang_n,']');
                }
                if(cefang_n.contains(" ")){
                    cefang_n=StringUtil.deleteCharString(cefang_n,' ');
                }
                String cefang = beanIDList.toString();
//                cefang = cefang.replace("[", "");
//                cefang = cefang.replace("]", "");
//                cefang = cefang.replaceAll(" ", "");
                if(cefang.contains("[")){
                    cefang=StringUtil.deleteCharString(cefang,'[');
                }
                if(cefang.contains("]")){
                    cefang=StringUtil.deleteCharString(cefang,']');
                }
                if(cefang.contains(" ")){
                    cefang=StringUtil.deleteCharString(cefang,' ');
                }

                addNewTvCefang.setText(cefang_n);

                addnewentity.setCefang_n(cefang_n);
                addnewentity.setCefang(cefang);

            }
        });

//        Log.i("厕房显示", "内容: "+addnewentity.getCefang_n());
//        Log.i("厕房显示", "ID: "+addnewentity.getCefang());

    }

    /**
     * 获取水冲方式数据
     *
     * @param view
     */
    private void getShuichongTYpe(final View view) {
        showLoadingDialog("水冲方式...");
        String the_last = HttpApis.addnew_chongshui;
        Log.i("水冲方式", "url: " + the_last);
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);
        HttpUtils.requestGet(_mActivity, the_last,map, new Request() {
            @Override
            public void success(String jsonStr) {
                super.success(jsonStr);

                Log.i("水冲方式", "success: " + jsonStr);

                Type type = new TypeToken<ArrayList<AddNewShiGongTeamEntity>>() {
                }.getType();


                shuichongEntityList = JsonUtil.json2Collection(jsonStr, type);

                showChongShuiPopu(view);

                cancelLoadingDialog();
            }

            @Override
            public void error(String error) {
                super.error(error);
                Log.i("便池类型", "error: " + error);

                cancelLoadingDialog();
            }
        });
    }

    /**
     * 加载冲水数据
     *
     * @param view
     */
    private void showChongShuiPopu(View view) {
        chongshuiPopupWindow = new ListPopupWindow(_mActivity);
        setShigTeamPopuData(view, chongshuiPopupWindow, shuichongEntityList);
        setShigongTeamPopuClickListener(new AddNewShigTeamPopuListener() {
            @Override
            public void show(AddNewShiGongTeamEntity cetity, String mess) {
                addNewTvChongshui.setText(mess);

                addnewentity.setChongshuifangshi(cetity.getValue());
                addnewentity.setChongshuifangshi_n(cetity.getText());
            }
        });

    }

    /**
     * 获取便池的数据
     *
     * @param view
     */
    private void getBianchiType(final View view) {
        showLoadingDialog("便池类型...");
        String the_last = HttpApis.addnew_banchitype;
        Log.i("便池类型", "url: " + the_last);
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);
        HttpUtils.requestGet(_mActivity, the_last,map, new Request() {
            @Override
            public void success(String jsonStr) {
                super.success(jsonStr);

                Log.i("便池类型", "success: " + jsonStr);

                Type type = new TypeToken<ArrayList<AddNewShiGongTeamEntity>>() {
                }.getType();


                bainchiEntityList = JsonUtil.json2Collection(jsonStr, type);

                showBianchiPopu(view);

                cancelLoadingDialog();
            }

            @Override
            public void error(String error) {
                super.error(error);
                Log.i("便池类型", "error: " + error);

                cancelLoadingDialog();
            }
        });
    }

    /**
     * 显示便池数据
     *
     * @param view
     */
    private void showBianchiPopu(View view) {
        ListPopupWindow bianchiPopupWindow = new ListPopupWindow(_mActivity);
        setShigTeamPopuData(view, bianchiPopupWindow, bainchiEntityList);
        setShigongTeamPopuClickListener(new AddNewShigTeamPopuListener() {
            @Override
            public void show(AddNewShiGongTeamEntity cetity, String mess) {
                addNewTvBianchi.setText(mess);

                addnewentity.setBianchi(cetity.getValue());
                addnewentity.setBianchi_n(cetity.getText());
            }
        });
    }


    /**
     * 获取化粪池材料数据
     *
     * @param view
     */
    private void getHuaFenChiCailiao(final View view) {
        showLoadingDialog("化粪池材料...");
        String the_last = HttpApis.addnew_huafenchi;
        Log.i("化粪池材料", "url: " + the_last);
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);
        HttpUtils.requestGet(_mActivity, the_last,map, new Request() {
            @Override
            public void success(String jsonStr) {
                super.success(jsonStr);

                Log.i("化粪池材料", "success: " + jsonStr);

                Type type = new TypeToken<ArrayList<AddNewShiGongTeamEntity>>() {
                }.getType();

                huafenchiEntityList = JsonUtil.json2Collection(jsonStr, type);

                showHuaFenChiPopu(view);

                cancelLoadingDialog();
            }

            @Override
            public void error(String error) {
                super.error(error);
                Log.i("化粪池材料", "error: " + error);

                cancelLoadingDialog();
            }
        });

    }

    /**
     * 化粪池材料PopupWindow
     *
     * @param view
     */
    private void showHuaFenChiPopu(View view) {
        huafenchiPopupWindow = new ListPopupWindow(_mActivity);
        setShigTeamPopuData(view, huafenchiPopupWindow, huafenchiEntityList);
        setShigongTeamPopuClickListener(new AddNewShigTeamPopuListener() {
            @Override
            public void show(AddNewShiGongTeamEntity cetity, String mess) {
                addNewTvHuafeichi.setText(mess);

                addnewentity.setHfc_material(cetity.getValue());
                addnewentity.setHfc_material_n(cetity.getText());

            }
        });

    }

    /**
     * 根据村级id获取户编号数据
     *
     * @param value
     */
    private void getHubianhaoData(String value) {
        showLoadingDialog("户编号...");
        if (!TextUtils.isEmpty(value) && value != null) {
            String hubiahao_url = HttpApis.addnew_hubianhao;
            Log.i("户编号数据", "url: " + hubiahao_url);
            Map<String, String> huparams = new TreeMap<>();
            huparams.put("area_id", value);
            huparams.put("token",token_data);
            HttpUtils.requestPost(_mActivity, hubiahao_url, huparams, new Request() {

                @Override
                public void success(String jsonStr) {
                    super.success(jsonStr);
                    Log.i("户编号数据", "success: " + jsonStr);

                    addNewEtDoornumberning.setText(jsonStr);

                    cancelLoadingDialog();
                }

                @Override
                public void error(String error) {
                    super.error(error);
                    Log.i("户编号数据", "error: " + error);
                    cancelLoadingDialog();
                }
            });
        }


    }

    /**
     * 根据状态显示要上传的值
     */
    private void UpShowForState(String tv_statue) {

        Log.i("UpShowForState", "UpShowForState: ");
        //String tv_statue = addNewTvBuildstate.getText().toString().trim();
        Log.i("UpShowForState", "UpShowForState: " + tv_statue);
        if (!TextUtils.isEmpty(tv_statue)) {
            switch (tv_statue) {
                case "未改造":

                    if(buildyearList.contains("2017")){
                        buildyearList.remove("2017");
                    }
                    //不需要录入改造类型、施工队名称和化粪池材料
//                    addNewTvBuildtype.setVisibility(View.INVISIBLE);
//                    addNewTvTeamname.setVisibility(View.INVISIBLE);
//
//                    addNewTvHuafeichi.setVisibility(View.INVISIBLE);
//                    addNewTvBianchi.setVisibility(View.INVISIBLE);
//                    addNewTvChongshui.setVisibility(View.INVISIBLE);
//                    addNewTvCefang.setVisibility(View.INVISIBLE);
//                    //需上传身份证照片、大门照和改造前照片
//                    //则改造中,改造后需要隐藏
//                    upAllIng.setVisibility(View.GONE);
//                    upAllAfter.setVisibility(View.GONE);

                    upAllIdpic.setVisibility(View.VISIBLE);
                    upAllBefore.setVisibility(View.VISIBLE);
                    upAllIng.setVisibility(View.VISIBLE);
                    upAllGaizaozhongtwo.setVisibility(View.VISIBLE);
                    upAllGaizaozhongthree.setVisibility(View.VISIBLE);
                    Log.i("UpShowForState", "未改造: " + tv_statue);

                    break;
                case "改造中":

                    if(buildyearList.contains("2017")){
                        buildyearList.remove("2017");
                    }
                    //需要选择改造类型、施工队名称、化粪池材料，
                    // 上传图片包括身份证、大门照、改造前和改造中
//                    upAllAfter.setVisibility(View.GONE);
//                    Log.i("UpShowForState", "改造中: " + tv_statue);
//                    addNewTvBuildtype.setVisibility(View.VISIBLE);
//                    addNewTvTeamname.setVisibility(View.VISIBLE);
//                    addNewTvHuafeichi.setVisibility(View.VISIBLE);
//                    upAllIng.setVisibility(View.VISIBLE);
//
//                    addNewTvBianchi.setVisibility(View.INVISIBLE);
//                    addNewTvChongshui.setVisibility(View.INVISIBLE);
//                    addNewTvCefang.setVisibility(View.INVISIBLE);

                    upAllIdpic.setVisibility(View.VISIBLE);
                    upAllBefore.setVisibility(View.VISIBLE);
                    upAllIng.setVisibility(View.VISIBLE);
                    upAllGaizaozhongtwo.setVisibility(View.VISIBLE);
                    upAllGaizaozhongthree.setVisibility(View.VISIBLE);


                    break;

                case "已改造":

                    if(buildyearList.contains("2017")){
                        buildyearList.remove("2017");
                    }
//                在改造中限制基础上增加需上传改造后照片。
//                就是什么都不用限制

//                    addNewTvBuildtype.setVisibility(View.VISIBLE);
//                    addNewTvTeamname.setVisibility(View.VISIBLE);
//                    upAllIng.setVisibility(View.VISIBLE);
//                    upAllAfter.setVisibility(View.VISIBLE);
//
//                    addNewTvHuafeichi.setVisibility(View.VISIBLE);
//                    addNewTvBianchi.setVisibility(View.VISIBLE);
//                    addNewTvChongshui.setVisibility(View.VISIBLE);
//                    addNewTvCefang.setVisibility(View.VISIBLE);
                    upAllIdpic.setVisibility(View.VISIBLE);
                    upAllBefore.setVisibility(View.VISIBLE);
                    upAllIng.setVisibility(View.VISIBLE);
                    upAllGaizaozhongtwo.setVisibility(View.VISIBLE);
                    upAllGaizaozhongthree.setVisibility(View.VISIBLE);


                    break;

                case "旧有改造":
                    upAllIdpic.setVisibility(View.VISIBLE);
                    upAllBefore.setVisibility(View.VISIBLE);
                    upAllIng.setVisibility(View.VISIBLE);
                    upAllGaizaozhongtwo.setVisibility(View.VISIBLE);
                    upAllGaizaozhongthree.setVisibility(View.VISIBLE);

                    if(!buildyearList.contains("2017")){
                        buildyearList.add(0,"2017");
                    }

                    break;

                default:
//                    addNewTvBuildtype.setVisibility(View.VISIBLE);
//                    addNewTvTeamname.setVisibility(View.VISIBLE);
//                    addNewTvHuafeichi.setVisibility(View.VISIBLE);
//                    upAllIng.setVisibility(View.VISIBLE);
//                    upAllAfter.setVisibility(View.VISIBLE);
//
//                    addNewTvBianchi.setVisibility(View.INVISIBLE);
//                    addNewTvChongshui.setVisibility(View.INVISIBLE);
//                    addNewTvCefang.setVisibility(View.INVISIBLE);

                    break;
            }
        }


    }

    //模拟输出测验
    private void syso(Map<String, String> conditionmap) {
        Set<Map.Entry<String, String>> entrySet = conditionmap.entrySet();
        Iterator<Map.Entry<String, String>> iterator = entrySet.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> me = iterator.next();
            String key = me.getKey();
            String value = me.getValue();

            Log.i("conditionmap", key + ":" + value);

        }

    }

    /**
     * 得到当前时间
     */
    private String getNowTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        return str;
    }

    /**
     * 上传数据
     */
    private void AddNewUpFildData() {
        String url_addnew_up = HttpApis.addnew_save;

        //后来补加
        Log.i("获取当前时间", "AddNewUpFildData: " + getNowTime());

        addnewentity.setIdfield("gaizao_id");
        addnewentity.setState_id("dengji");


        addnewentity.setBuchongfu(getNowTime());
        addnewentity.setToken(token_data);
//        HashMap<String, String> map = new HashMap<>();
//        map.put("token",token_data);
        syso(saveparams);


        HttpUtils.requestPostGson(_mActivity, url_addnew_up, addnewentity, new Request() {

            @Override
            public void success(String jsonStr) {
                super.success(jsonStr);

                try{
                    Log.i("addnew提交数据", "success: " + jsonStr);

                    FIleEditSaveUpEntity getdata = GsonTools.changeGsonToBean(jsonStr, FIleEditSaveUpEntity.class);
                    if ("success".equals(getdata.getState())) {
                        Toast.makeText(_mActivity, "保存提交成功", Toast.LENGTH_SHORT).show();

                        //恢复默认值
                        //add_newaddress_Contry.setText("县");
                        add_newaddress_Town.setText("乡(镇)");
                        addNewEtAddress_village.setText("村");
                        addNewEtDoorcode.setText("");
                        addNewEtDoorname.setText("");
                        addNewEtDoornumberning.setText("");
                        addNewEtIdnumber.setText("");
                        addNewTvIsIdel.setText("");
                        addNewTvBuildstate.setText("");
                        addNewTvBuildtype.setText("");
                        addNewTvTeamname.setText("");
                        addNewTvHuafeichi.setText("");

                        addNewTvBianchi.setText("");
                        addNewTvChongshui.setText("");
                        addNewTvCefang.setText("");

                        //图片状态重置
                        sellIvMyFileOne.setVisibility(View.VISIBLE);
                        sellIvMyFileTwo.setVisibility(View.VISIBLE);
                        sellIvMyFileThree.setVisibility(View.VISIBLE);
                        sellIvMyFileFour.setVisibility(View.VISIBLE);
                        sellIvMyFileFive.setVisibility(View.VISIBLE);
                        sellIvGaizaozhongtwo.setVisibility(View.VISIBLE);
                        sellIvGaizaozhongthree.setVisibility(View.VISIBLE);
                        image_show_B.setVisibility(View.GONE);
                        image_show_M.setVisibility(View.GONE);
                        image_show_F.setVisibility(View.GONE);
                        image_show_ID.setVisibility(View.GONE);
                        image_show_D.setVisibility(View.GONE);
                        sellIvGaizaozhongtwo.setVisibility(View.GONE);
                        sellIvGaizaozhongthree.setVisibility(View.GONE);

                        //清空集合
                        saveparams.clear();

                        if (addnewentity != null) {
                            addnewentity = null;
                        }

                        //比如 未改造 设置为 已改造 时,刷新界面,状态改变
                        EventBus.getDefault().post(new MessageEvent("370"));

                        //保存成功后回到列表页
                        _mActivity.onBackPressed();


                    } else if ("repeat".equals(getdata.getState())) {
                        Toast.makeText(_mActivity, "重复提交", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(_mActivity, "提交失败", Toast.LENGTH_SHORT).show();
                    }

                    cancelLoadingDialog();
                }catch (Exception e){

                }


            }

            @Override
            public void error(String error) {
                super.error(error);
                Log.i("addnew提交数据", "error: " + error);

                cancelLoadingDialog();
            }

        });

    }

    /**
     * 检查各个字段对应的数值,辖区单位进行拼接
     */
    private boolean CheckFildValue() {
        //辖区单位
        String conty = add_newaddress_Contry.getText().toString().trim();
        String town = add_newaddress_Town.getText().toString().trim();
        String village = addNewEtAddress_village.getText().toString().trim();
        if ( !"乡(镇)".equals(conty) && !"村".equals(conty)) {//!"县".equals(conty) &&
            addnewentity.setArea_name(conty + town + village);

        } else {
            //Toast.makeText(_mActivity, "请选择辖区单位", Toast.LENGTH_SHORT).show();
            showAlertOnlyPos(_mActivity, "辖区单位", "请选择辖区单位");
            return false;
        }


        //户名  addNewEtDoorname
        String huming = addNewEtDoorname.getText().toString().trim();
        if (TextUtils.isEmpty(huming)) {
            //Toast.makeText(_mActivity, "请输入正确的户名", Toast.LENGTH_SHORT).show();
            showAlertOnlyPos(_mActivity, "户名", "请输入正确户名");
            return false;
        } else if (!huming.matches("[\u4e00-\u9fa5]+")) {
            //Toast.makeText(_mActivity, "户名格式请输入汉字", Toast.LENGTH_SHORT).show();
            showAlertOnlyPos(_mActivity, "户名", "户名格式请输入汉字");
            return false;
        } else {
            addnewentity.setHuming(huming);
        }

        //家庭人口
        String humans = addNewEtHumans.getText().toString().trim();
        if (!TextUtils.isEmpty(humans)) {
            int human_num = Integer.parseInt(humans);
            if (human_num <= 0 || human_num >= 100) {
                //showShortToast("家庭人口请输入1~100以内整数");
                showAlertOnlyPos(_mActivity, "家庭人口", "请输入1~100以内整数");
                return false;
            } else {
                addnewentity.setRenkou(humans);
            }

        }
//        else {
//            //showShortToast("请输入家庭人口");
//            showAlertOnlyPos(_mActivity, "家庭人口", "请输入家庭人口");
//            return false;
//        }

        //联系电话
        String human_tel = addNewEtTel.getText().toString().trim();
        if (!TextUtils.isEmpty(human_tel)) {
            if (RegexUtils.isMobileExact(human_tel)) {
                addnewentity.setPhone(human_tel);
            } else {
                showAlertOnlyPos(_mActivity, "联系电话", "请输入正确电话号码");
                return false;
            }
        }
//        else {
//            //showShortToast("请输入联系电话");
//            showAlertOnlyPos(_mActivity, "联系电话", "请输入联系电话");
//            return false;
//        }

        //户编号  自动生成,不可编辑
//        String hubianhao = addNewEtDoornumberning.getText().toString().trim();
//        if (TextUtils.isEmpty(hubianhao)) {
//            //Toast.makeText(_mActivity, "请确定完整输入辖区单位", Toast.LENGTH_SHORT).show();
//            showAlertOnlyPos(_mActivity, "户编号数据", "自动生成,不可编辑");
//            return false;
//        } else {
//            addnewentity.setHubianhao(hubianhao);
//        }
        //身份证号  add_new_et_idnumber
        String shenfenzhenghao = addNewEtIdnumber.getText().toString().trim();
        if (TextUtils.isEmpty(shenfenzhenghao)) {
            showAlertOnlyPos(_mActivity, "身份证号", "请输入正确的身份证号");
            return false;
        } else if (!RegexUtils.isIDCard18(shenfenzhenghao)) {
            showAlertOnlyPos(_mActivity, "身份证号", "身份证号格式不正确");
            return false;
        } else if (getCheckAge(shenfenzhenghao)) {
            showAlertOnlyPos(_mActivity,"身份证号","要求年龄大于18岁");
            return false;
        } else if(RegexUtils.isIDCard18(shenfenzhenghao)&&shenfenzhenghao.contains("x")){
            showAlertOnlyPos(_mActivity,"身份证号","要求尾字母大写");
            return false;
        } else {
            addnewentity.setCert_no_sec(shenfenzhenghao);
        }

        //是否闲置 addNewTvIsIdel
        String isIdle = addNewTvIsIdel.getText().toString().trim();
        if (TextUtils.isEmpty(isIdle)) {
            showAlertOnlyPos(_mActivity,"是否闲置","请选择是否闲置");
            return false;
        } else {
            if ("是".equals(isIdle)) {
                addnewentity.setXianzhi("1");
                addnewentity.setXianzhi_n("是");
            } else if ("否".equals(isIdle)) {
                addnewentity.setXianzhi("0");
                addnewentity.setXianzhi_n("否");
            }

        }

        //改造状态 addNewTvBuildstate
        String build_state = addNewTvBuildstate.getText().toString().trim();
        if ("否".equals(isIdle) && TextUtils.isEmpty(build_state)) {
            showAlertOnlyPos(_mActivity,"改造状态","请选择改造状态");
            return false;

        }

        addnewentity.setGaizao_state_n(build_state);
        switch (build_state) {
            case "已改造":
                // saveparams.put("gaizao_state", "403");
                addnewentity.setGaizao_state("403");
                break;
            case "改造中":
                ///saveparams.put("gaizao_state", "402");
                addnewentity.setGaizao_state("402");
                break;
            case "未改造":
                // saveparams.put("gaizao_state", "401");
                addnewentity.setGaizao_state("401");
                break;
            case "旧有改造":
                //  saveparams.put("gaizao_state", "404");
                addnewentity.setGaizao_state("404");
                break;

            default:

                break;
        }


//        addnewentity.setAdjunct_id(new String[]{before_ima[0], ing_ima[0], after_ima[0], idcard_ima[0], fodoor_ima[0],ing_two_ima[0],ing_three_ima[0]});
//        addnewentity.setSys_file_name(new String[]{before_ima[1], ing_ima[1], after_ima[1], idcard_ima[1], fodoor_ima[1],ing_two_ima[1],ing_three_ima[1]});
//        addnewentity.setAdjunct_type(new String[]{before_ima[2], ing_ima[2], after_ima[2], idcard_ima[2], fodoor_ima[2],ing_two_ima[2],ing_three_ima[2]});
//        addnewentity.setFile_type(new String[]{before_ima[3], ing_ima[3], after_ima[3], idcard_ima[3], fodoor_ima[3],ing_two_ima[3],ing_three_ima[3]});
//        addnewentity.setFile_size(new String[]{before_ima[4], ing_ima[4], after_ima[4], idcard_ima[4], fodoor_ima[4],ing_two_ima[4],ing_three_ima[4]});
//        addnewentity.setFile_des(new String[]{before_ima[5], ing_ima[5], after_ima[5], idcard_ima[5], fodoor_ima[5],ing_two_ima[5],ing_three_ima[5]});
//        addnewentity.setUser_file_name(new String[]{before_ima[6], ing_ima[6], after_ima[6], idcard_ima[6], fodoor_ima[6],ing_two_ima[6],ing_three_ima[6]});


        String[] arr_adjunct_id=new String[]{before_ima[0], ing_ima[0], after_ima[0], idcard_ima[0], fodoor_ima[0],ing_two_ima[0],ing_three_ima[0]};

        arr_adjunct_id=arrayRemoveSpace(arr_adjunct_id);

        String[] arr_sys_file_name=new String[]{before_ima[1], ing_ima[1], after_ima[1], idcard_ima[1], fodoor_ima[1],ing_two_ima[1],ing_three_ima[1]};
        arr_sys_file_name=arrayRemoveSpace(arr_sys_file_name);

        String[] arr_adjunct_type=new String[]{before_ima[2], ing_ima[2], after_ima[2], idcard_ima[2], fodoor_ima[2],ing_two_ima[2],ing_three_ima[2]};
        arr_adjunct_type=arrayRemoveSpace(arr_adjunct_type);

        String[] arr_file_type=new String[]{before_ima[3], ing_ima[3], after_ima[3], idcard_ima[3], fodoor_ima[3],ing_two_ima[3],ing_three_ima[3]};
        arr_file_type=arrayRemoveSpace(arr_file_type);

        String[] arr_file_size=new String[]{before_ima[4], ing_ima[4], after_ima[4], idcard_ima[4], fodoor_ima[4],ing_two_ima[4],ing_three_ima[4]};
        arr_file_size=arrayRemoveSpace(arr_file_size);

        String[] arr_file_des=new String[]{before_ima[5], ing_ima[5], after_ima[5], idcard_ima[5], fodoor_ima[5],ing_two_ima[5],ing_three_ima[5]};
        arr_file_des=arrayRemoveSpace(arr_file_des);

        String[] arr_user_file_name=new String[]{before_ima[6], ing_ima[6], after_ima[6], idcard_ima[6], fodoor_ima[6],ing_two_ima[6],ing_three_ima[6]};
        arr_user_file_name=arrayRemoveSpace(arr_user_file_name);

        String[] arr_picmd5code=new String[]{before_ima[7], ing_ima[7], after_ima[7], idcard_ima[7], fodoor_ima[7],ing_two_ima[7],ing_three_ima[7]};
        arr_picmd5code=arrayRemoveSpace(arr_picmd5code);

        addnewentity.setAdjunct_id(arr_adjunct_id);
        addnewentity.setSys_file_name(arr_sys_file_name);
        addnewentity.setAdjunct_type(arr_adjunct_type);
        addnewentity.setFile_type(arr_file_type);
        addnewentity.setFile_size(arr_file_size);
        addnewentity.setFile_des(arr_file_des);
        addnewentity.setUser_file_name(arr_user_file_name);
        addnewentity.setPicmd5code(arr_picmd5code);


        //======================校验====================================================
        String isIdle_value = addNewTvIsIdel.getText().toString().trim();
        if ("否".equals(isIdle_value)) {
            String build_state_value = addNewTvBuildstate.getText().toString().trim();
            String addNewBuildyear = addNewTvBuildyear.getText().toString().trim();
            String buildStyle = addNewTvBuildStyle.getText().toString().trim();
            String build_type_name = addNewTvBuildtype.getText().toString().trim();
            switch (build_state_value) {
                case "已改造":


                    //任务年份 *必填项
                    if(TextUtils.isEmpty(addNewBuildyear)){
                        showAlertOnlyPos(_mActivity,"任务年份","请选择任务年份");
                        cancelLoadingDialog();
                        return false;
                    }

                    //改造类型
                    String build_type_names = addNewTvBuildtype.getText().toString().trim();
                    if (TextUtils.isEmpty(build_type_names)) {
                        showAlertOnlyPos(_mActivity, "改造类型", "请选择改造类型");
                        return false;
                    }


                    //改厕方式   改造中，已改造为必填
                    //String buildStyle = addNewTvBuildStyle.getText().toString().trim();
                    if(TextUtils.isEmpty(buildStyle)){
                        showAlertOnlyPos(_mActivity,"改厕方式","请选择改厕方式");
                        return false;
                    }else{

                        if("农户自改自建".equals(buildStyle)){
                            addnewentity.setGaizao_fangshi_n("农户自改自建");
                            addnewentity.setGaizao_fangshi("1001");
                        }else if("政府主导统一施工".equals(buildStyle)){
                            addnewentity.setGaizao_fangshi_n("政府主导统一施工");
                            addnewentity.setGaizao_fangshi("1002");
                        }
                    }

                    //施工队名称
                    String shigteamnames = addNewTvTeamname.getText().toString().trim();
                    if (TextUtils.isEmpty(shigteamnames)) {
                        showAlertOnlyPos(_mActivity, "施工队名称", "请选择施工队伍");
                        return false;
                    }
                    // TODO: 2018/7/13 化粪池材料 已更改为选填项 化粪池材料、便池、冲水方式、和厕房字段在已改造状态时要求为必填；
                    //化粪池材料
//                    String huafcMs = addNewTvHuafeichi.getText().toString().trim();
//                    if (TextUtils.isEmpty(huafcMs)) {
//                        showAlertOnlyPos(_mActivity, "化粪池材料", "请输入化粪池材料");
//                        return false;
//                    }
                    //便池类型
//                    String bianchitype = addNewTvBianchi.getText().toString().trim();
//                    if (TextUtils.isEmpty(bianchitype)) {
//                        //Toast.makeText(_mActivity, "请输入便池类型", Toast.LENGTH_SHORT).show();
//                        showAlertOnlyPos(_mActivity, "便池类型", "请输入便池类型");
//                        return false;
//                    }

                    //冲水方式
//                    String chongshuitype = addNewTvChongshui.getText().toString().trim();
//                    if (TextUtils.isEmpty(chongshuitype)) {
//                        showAlertOnlyPos(_mActivity, "冲水方式", "请输入冲水方式");
//                        return false;
//                    }

                    //厕房类型
//                    String cefangtype = addNewTvCefang.getText().toString().trim();
//                    if (TextUtils.isEmpty(cefangtype)) {
//                        //Toast.makeText(_mActivity, "请输入厕房类型", Toast.LENGTH_SHORT).show();
//                        showAlertOnlyPos(_mActivity, "厕房类型", "请输入厕房类型");
//                        return false;
//                    }


                    //身份证正面、大门照、改造前、改造中、改造后
//                    if (!isImageMidSuccess || !isImageAfSuccess ||
//                            !isImageIdSuccess || !isImageDoorFontSuccess ||
//                            !isImageBfSuccess) {
//                        //showShortToast("请上传身份证正面照片,大门前照片,改造前照片,改造中照片和改造后照片");
//                        showAlertOnlyPos(_mActivity, "照片附件", "请上传身份证正面照片,大门前照片,改造前照片,改造中照片和改造后照片");
//                        cancelLoadingDialog();
//                        return false;
//                    }
                    if (!isImageAfSuccess  || !isImageDoorFontSuccess) {
                        showAlertOnlyPos(_mActivity, "照片附件", "请上传大门照照片,改造后照片");
                        cancelLoadingDialog();
                        return false;
                    }

//                    if(!isImageMidTwoSuccess||!isImageMidThreeSuccess){
//                        showAlertOnlyPos(_mActivity, "照片附件", "请上传改造中2照片和改造中3照片");
//                        cancelLoadingDialog();
//                        return false;
//                    }

                    if("沼气池改良式".equals(build_type_name)||"通风改良+粪便集中无害化式".equals(build_type_name)){

                    }else{
//                        if(!isImageMidSuccess){
//                            showAlertOnlyPos(_mActivity, "照片附件", "请上传改造中1照片");
//                            cancelLoadingDialog();
//                            return false;
//                        }
                    }


                    break;
                case "改造中":

                    //改造中 必填项：改造类型、施工队名称、化粪池材料、身份证正面、大门照、改造前、改造中
                    //

                    //任务年份 *必填项
                    if(TextUtils.isEmpty(addNewBuildyear)){
                        showAlertOnlyPos(_mActivity,"任务年份","请选择任务年份");
                        cancelLoadingDialog();
                        return false;
                    }

                    //改造类型
                    //String build_type_name = addNewTvBuildtype.getText().toString().trim();
                    if (TextUtils.isEmpty(build_type_name)) {
                        showAlertOnlyPos(_mActivity, "改造类型", "请输入改造类型");
                        return false;
                    }

                    //改厕方式   改造中，已改造为必填
                    //String buildStyle = addNewTvBuildStyle.getText().toString().trim();
                    if(TextUtils.isEmpty(buildStyle)){
                        showAlertOnlyPos(_mActivity,"改厕方式","请选择改厕方式");
                        return false;
                    }else{

                        if("农户自改自建".equals(buildStyle)){
                            addnewentity.setGaizao_fangshi_n("农户自改自建");
                            addnewentity.setGaizao_fangshi("1001");
                        }else if("政府主导统一施工".equals(buildStyle)){
                            addnewentity.setGaizao_fangshi_n("政府主导统一施工");
                            addnewentity.setGaizao_fangshi("1002");
                        }
                    }

                    //冲水方式  非必填
//                    String chuiShuifangshi = addNewTvChongshui.getText().toString().trim();
//                    if (TextUtils.isEmpty(chuiShuifangshi)) {
//                        showAlertOnlyPos(_mActivity, "冲水方式", "请选择冲水方式");
//                        return false;
//                    }


                    //施工队名称
                    String shigteamname = addNewTvTeamname.getText().toString().trim();
                    if (TextUtils.isEmpty(shigteamname)) {
                        showAlertOnlyPos(_mActivity, "施工队名称", "请选择施工队伍");
                        return false;
                    }
                    //化粪池材料
                    String huafcM = addNewTvHuafeichi.getText().toString().trim();
//                    if (TextUtils.isEmpty(huafcM)) {
//                        showAlertOnlyPos(_mActivity, "化粪池材料", "请输入化粪池材料");
//                        return false;
//                    } else {
//                        addnewentity.setHfc_material_n(huafcM);
//                    }
                    addnewentity.setHfc_material_n(huafcM);

                    //身份证正面、大门照、改造前、改造中
//                    if (!isImageMidSuccess || !isImageAfSuccess || !isImageIdSuccess || !isImageDoorFontSuccess) {
//                        //showShortToast("请上传身份证正面照片,大门前照片,改造前照片和改造中照片");
//                        showAlertOnlyPos(_mActivity, "照片附件", "");
//                        cancelLoadingDialog();
//                        return false;
//                    }
                    if (!isImageDoorFontSuccess) {
                        showAlertOnlyPos(_mActivity, "照片附件", "请上传大门照照片");
                        cancelLoadingDialog();
                        return false;
                    }






                    break;
                case "未改造":

                    //必填项   身份证正面、大门照、改造前

                    //Log.i("未改造时图片的数据状态", "AddNewUpFildData: isImageMidSuccess:" +isImageMidSuccess
                    //+"~~isImageAfSuccess:"+isImageAfSuccess
                    //+"~~isImageIdSuccess"+isImageIdSuccess);

//                    if (!isImageMidSuccess || !isImageAfSuccess || !isImageIdSuccess) {
//                        //showShortToast("请上传身份证正面照片,大门前照片和改造前照片");
//                        showAlertOnlyPos(_mActivity, "照片附件", "上传身份证正面照片,大门前照片和改造前照片");
//                        cancelLoadingDialog();
//                        return false;
//                    }

                    if(TextUtils.isEmpty(build_type_name)){
                        addnewentity.setGaizao_type("-1");
                        addnewentity.setGaizao_type_n("");
                    }

                    //未改造状态  任务年份 *必填项

                    if("农户自改自建".equals(buildStyle)){
                        addnewentity.setGaizao_fangshi_n("农户自改自建");
                        addnewentity.setGaizao_fangshi("1001");
                    }else if("政府主导统一施工".equals(buildStyle)){
                        addnewentity.setGaizao_fangshi_n("政府主导统一施工");
                        addnewentity.setGaizao_fangshi("1002");
                    }

                    if(TextUtils.isEmpty(addNewBuildyear)){
                        showAlertOnlyPos(_mActivity,"任务年份","请选择任务年份");
                        cancelLoadingDialog();
                        return false;
                    }

                    //未改造 状态 改厕方式是非必填



                    break;
                case "旧有改造":

                    //改造类型
//                    String build_type_namea = addNewTvBuildtype.getText().toString().trim();
//                    if (TextUtils.isEmpty(build_type_namea)) {
//                        showAlertOnlyPos(_mActivity, "改造类型", "请选择改造类型");
//                        return false;
//                    }

                    break;

                default:

                    break;
            }

        }

        //改厕方式   改造中，已改造为必填
//        String buildStyle = addNewTvBuildStyle.getText().toString().trim();
//        if(TextUtils.isEmpty(buildStyle)){
//            showAlertOnlyPos(_mActivity,"改厕方式","请选择改厕方式");
//            return false;
//        }else{
//
//            if("农户自改自建".equals(buildStyle)){
//                addnewentity.setGaizao_fangshi_n("农户自改自建");
//                addnewentity.setGaizao_fangshi("1001");
//            }else if("政府主导统一施工".equals(buildStyle)){
//                addnewentity.setGaizao_fangshi_n("政府主导统一施工");
//                addnewentity.setGaizao_fangshi("1002");
//            }
//        }

        //判断登记人  *必填项
//        String dengJiRen = addNewTvDengjiren.getText().toString().trim();
//        if (TextUtils.isEmpty(dengJiRen)) {
//            showAlertOnlyPos(_mActivity,"登记人","请选择登记人");
//            return false;
//        } else {
//
//        }

        //判断最新操作时间   *必填项
//        String caoZuoshijian = addNewTvCaozuotime.getText().toString().trim();
//        if(TextUtils.isEmpty(caoZuoshijian)){
//            showAlertOnlyPos(_mActivity,"最新操作时间","请选择操作时间");
//            return false;
//        }else{
//
//        }


        //无论什么情况,总是上传门牌号和化粪池材料
//        String huafcMs_any = addNewTvHuafeichi.getText().toString().trim();
//        if (!TextUtils.isEmpty(huafcMs_any)){
//            addnewentity.setHfc_material(huafcMs_any);
//        }
        //addnewentity.setMenpaihao(menpaihao);




        return true;


    }

    private String[] arrayRemoveSpace(String[] arr_adjunct_id){

        List<String> adjunct_id=new ArrayList<>();
        for (int i=0;i<arr_adjunct_id.length;i++) {
            if(arr_adjunct_id[i]!=null){
                adjunct_id.add(arr_adjunct_id[i]);
            }
        }
        arr_adjunct_id=adjunct_id.toArray(new String[adjunct_id.size()]);

        return arr_adjunct_id;

    }

    /**
     * 判断是否大于18岁
     *
     * @param shenfenzhenghao
     * @return
     */
    private boolean getCheckAge(String shenfenzhenghao) {

        //获取当前时间年份
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
        Date curDate = new Date(System.currentTimeMillis());
        String str = formatter.format(curDate);
        int now_year = Integer.parseInt(str);

        //获取身份证年份
        String chkidcard = shenfenzhenghao.substring(6, 10);
        int idcard_year = Integer.parseInt(chkidcard);


        if (now_year - idcard_year >= 18) {
            return false;
        } else {
            return true;
        }


    }


    /**
     * 获取施工队数据
     *
     * @param village_value
     */
    private void getShigongTeamData(final View view, String village_value) {
        Log.i("施工队", "getShigongTeamData: " + village_value);

        showLoadingDialog("施工队...");

        String shigongteamUrl = HttpApis.addnew_teamdata + village_value;
        Log.i("施工队", "url: " + shigongteamUrl);
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);
        HttpUtils.requestGet(_mActivity, shigongteamUrl,map, new Request() {

            @Override
            public void success(String jsonStr) {
                super.success(jsonStr);

                Log.i("施工队", "success: " + jsonStr);

                Type type = new TypeToken<ArrayList<AddNewShiGongTeamEntity>>() {
                }.getType();

                addNewShigongteamEntityList = JsonUtil.json2Collection(jsonStr, type);

                showShigongTeamPopu(view);

                cancelLoadingDialog();
            }

            @Override
            public void error(String error) {
                super.error(error);
                Log.i("施工队", "error: " + error);

                cancelLoadingDialog();
            }
        });

    }


    /**
     * 根据改造状态获取改造类型
     */
    private void getStateType(View view) {
        String state_build = addNewTvBuildstate.getText().toString().trim();
        if (TextUtils.isEmpty(state_build) || state_build == null) {
            Toast.makeText(_mActivity, "请先选择改造状态", Toast.LENGTH_SHORT).show();
            return;
        }
        switch (state_build) {
            case "已改造":
            case "未改造":
            case "改造中":
                showLoadingDialog("正在加载...");
                //getFontTypeData(view);
                getLastTypeData(view);
                break;
            case "旧有改造":
                showLoadingDialog("正在加载...");
                getLastTypeData(view);
                break;

            default:

                break;
        }
        //getLastTypeData(view);


    }

    /**
     * 获取前三种改造状态对应的改造类型
     */
    private void getFontTypeData(final View view) {
        String the_threeurl = HttpApis.addnew_fontThree;
        Log.i("前三个状态", "url: " + the_threeurl);
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);
        HttpUtils.requestGet(_mActivity, the_threeurl,map, new Request() {
            @Override
            public void success(String jsonStr) {
                super.success(jsonStr);

                Log.i("前三个状态", "success: " + jsonStr);

                Type type = new TypeToken<ArrayList<AddNewBuildTypeEntity>>() {
                }.getType();

                addNewBuildTypeEntityList = JsonUtil.json2Collection(jsonStr, type);

                showBuildTypePopu(view);

                cancelLoadingDialog();
            }

            @Override
            public void error(String error) {
                super.error(error);
                Log.i("前三个状态", "error: " + error);

                cancelLoadingDialog();
            }
        });

    }


    /**
     * 获取第四种改造状态对应的改造类型
     */
    private void getLastTypeData(final View view) {
        String the_last = HttpApis.addnew_last;
        Log.i("第四个状态", "url: " + the_last);
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);
        HttpUtils.requestGet(_mActivity, the_last,map, new Request() {
            @Override
            public void success(String jsonStr) {
                super.success(jsonStr);

                Log.i("第四个状态", "success: " + jsonStr);

                Type type = new TypeToken<ArrayList<AddNewBuildTypeEntity>>() {
                }.getType();

                addNewBuildTypeEntityList = JsonUtil.json2Collection(jsonStr, type);

                showBuildTypePopu(view);

                cancelLoadingDialog();
            }

            @Override
            public void error(String error) {
                super.error(error);
                Log.i("前三个状态", "error: " + error);

                cancelLoadingDialog();
            }
        });
    }


    /**
     * 显示改造类型popuwindow
     *
     * @param view
     */
    private void showBuildTypePopu(View view) {

        addnewtypelist.clear();
        beanTypeList.clear();
        beanTypeIDList.clear();

        addnewbtypePopupWindow = new ListPopupWindow(_mActivity);
        setbuildTypePopuData(view, addnewbtypePopupWindow, addNewBuildTypeEntityList);
//        setbuildTypePopuClickListener(new AddNewBuildTypePopuListener() {
//            @Override
//            public void show(AddNewBuildTypeEntity cetity, String mess) {
//                addNewTvBuildtype.setText(mess);
//                addnewentity.setGaizao_type_n(cetity.getText());
//                addnewentity.setGaizao_type(cetity.getValue());
//            }
//        });

        setbuildTypePopuClickListener(new BuildTypePopuListener() {
            @Override
            public void show(List<AddNewBuildTypeEntity> datalist) {
                beanTypeList.clear();
                beanTypeIDList.clear();

                for (AddNewBuildTypeEntity abte : addnewtypelist) {
                    //beanTypeList.add(abte.getText());
                    beanTypeIDList.add(abte.getValue());
                }

                Collections.sort(beanTypeIDList);

                for (String idValue: beanTypeIDList) {
                    if("201".equals(idValue)){
                        beanTypeList.add("厕屋");
                    }
                    if("202".equals(idValue)){
                        beanTypeList.add("便器");
                    }
                    if("203".equals(idValue)){
                        beanTypeList.add("化粪池");
                    }
                }




                String buildtype_n = beanTypeList.toString();
                if(buildtype_n.contains("[")){
                    buildtype_n= StringUtil.deleteCharString(buildtype_n,'[');
                }
                if(buildtype_n.contains("]")){
                    buildtype_n= StringUtil.deleteCharString(buildtype_n,']');
                }
                if(buildtype_n.contains(" ")){
                    buildtype_n=StringUtil.deleteCharString(buildtype_n,' ');
                }
                String buildtype_Id = beanTypeIDList.toString();
                if(buildtype_Id.contains("[")){
                    buildtype_Id=StringUtil.deleteCharString(buildtype_Id,'[');
                }
                if(buildtype_Id.contains("]")){
                    buildtype_Id=StringUtil.deleteCharString(buildtype_Id,']');
                }
                if(buildtype_Id.contains(" ")){
                    buildtype_Id=StringUtil.deleteCharString(buildtype_Id,' ');
                }

                addNewTvBuildtype.setText(buildtype_n);

                addnewentity.setGaizao_type_n(buildtype_n);
                addnewentity.setGaizao_type(buildtype_Id);
            }
        });
    }

    /**
     * 显示施工队popuwindow
     *
     * @param view
     */
    private void showShigongTeamPopu(View view) {
        addnewshigongteamPopupWindow = new ListPopupWindow(_mActivity);
        setShigTeamPopuData(view, addnewshigongteamPopupWindow, addNewShigongteamEntityList);
        setShigongTeamPopuClickListener(new AddNewShigTeamPopuListener() {
            @Override
            public void show(AddNewShiGongTeamEntity cetity, String mess) {
                addNewTvTeamname.setText(mess);

                // TODO: 2018/6/19 施工队
//                saveparams.put("shgd_name", cetity.getText());
//                saveparams.put("shgd_id", cetity.getValue());

                addnewentity.setShgd_name(cetity.getText());
                addnewentity.setShgd_id(cetity.getValue());
            }
        });
    }


//----------------------------厕房popudata---------------------------------------------------------------

    private int rosterIndex = 0;
    private List<AddNewShiGongTeamEntity> beanShowList = new ArrayList<>();
    private List<String> beanList = new ArrayList<>();
    private List<String> beanIDList = new ArrayList<>();
    private List<AddNewShiGongTeamEntity> mRosterList = new ArrayList<>();

    private void setCeFangPopuData(View view, final ListPopupWindow mPopupWindow, final List<AddNewShiGongTeamEntity> datalist) {


        myAdapter = new CeFangAdapter(_mActivity, datalist);

        mPopupWindow.setAdapter(myAdapter);

        //弹出的位置  弹出锚点
        mPopupWindow.setAnchorView(view);

        mPopupWindow.setVerticalOffset(ConvertUtils.dp2px(_mActivity, 16));
        //设置宽高
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);

        mPopupWindow.setModal(true);//设置模态框，设置为true响应物理键


        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {


//                beanList.clear();
//                beanIDList.clear();
                for (AddNewShiGongTeamEntity rb : beanShowList) {
                    beanList.add(rb.getText());
                    beanIDList.add(rb.getValue());
                }


                String cefang_n = removeRepeat(beanList).toString();
                if(cefang_n.contains("[")){
                    cefang_n= StringUtil.deleteCharString(cefang_n,'[');
                }
                if(cefang_n.contains("]")){
                    cefang_n= StringUtil.deleteCharString(cefang_n,']');
                }
                if(cefang_n.contains(" ")){
                    cefang_n=StringUtil.deleteCharString(cefang_n,' ');
                }

                addnewentity.setCefang_n(cefang_n);
                String cefang = removeRepeat(beanIDList).toString();
//                cefang = cefang.replace("[", "");
//                cefang = cefang.replace("]", "");
//                cefang = cefang.replaceAll(" ", "");
                if(cefang.contains("[")){
                    cefang=StringUtil.deleteCharString(cefang,'[');
                }
                if(cefang.contains("]")){
                    cefang=StringUtil.deleteCharString(cefang,']');
                }
                if(cefang.contains(" ")){
                    cefang=StringUtil.deleteCharString(cefang,' ');
                }
                addnewentity.setCefang(cefang);


                Log.i("厕房显示", "内容: " + addnewentity.getCefang_n());
                Log.i("厕房显示", "ID: " + addnewentity.getCefang());


                beanList.clear();
                beanIDList.clear();
            }
        });

        //设置条目点击事件
        mPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (datalist.get(position).isSelected() == false) {
                    rosterIndex++;
                    beanShowList.add(datalist.get(position));
                    datalist.get(position).setSelected(true);
                } else {
                    rosterIndex--;
                    if (beanShowList.contains(datalist.get(position))) {
                        beanShowList.remove(datalist.get(position));
                    }
                    datalist.get(position).setSelected(false);
                }
                if (rosterIndex == 0) {
                    addNewTvCefang.setText("");
                    beanShowList.clear();
                    mPopupWindow.dismiss();
                } else {
                    //使用回调,显示数据
                    if (cefangPopuListener != null) {
                        cefangPopuListener.show(beanShowList);
                    }
                }

                myAdapter.notifyDataSetChanged();
            }
        });
        mPopupWindow.show();
    }


    public CeFangPopuListener cefangPopuListener;

    public void setCeFangPopuClickListener(CeFangPopuListener cefangPopuListener) {
        this.cefangPopuListener = cefangPopuListener;
    }


    private List<String> removeRepeat(List<String> list) {
        List<String> no_list = new ArrayList<>();
        for (String show_str : list) {
            if (!no_list.contains(show_str)) {
                no_list.add(show_str);
            }
        }
        return no_list;
    }


//----------------------------施工队popudata---------------------------------------------------------------


    private List<String> addnewshigtlist = new ArrayList<>();

    private void setShigTeamPopuData(View view, final ListPopupWindow mPopupWindow, final List<AddNewShiGongTeamEntity> datalist) {

        addnewshigtlist.clear();
        for (AddNewShiGongTeamEntity abte : datalist) {
            addnewshigtlist.add(abte.getText());
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<>(_mActivity, android.R.layout.simple_list_item_1, addnewshigtlist);
        mPopupWindow.setAdapter(adapter);

        //弹出的位置  弹出锚点
        mPopupWindow.setAnchorView(view);
        //设置宽高
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);

        mPopupWindow.setModal(true);//设置模态框，设置为true响应物理键
        //设置条目点击事件
        mPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //使用回调,显示数据
                if (anshigongteamClickListener != null) {
                    anshigongteamClickListener.show(datalist.get(position), addnewshigtlist.get(position));
                }
                mPopupWindow.dismiss();
            }
        });
        mPopupWindow.show();
    }

    public AddNewShigTeamPopuListener anshigongteamClickListener;

    public void setShigongTeamPopuClickListener(AddNewShigTeamPopuListener anshigongteamClickListener) {
        this.anshigongteamClickListener = anshigongteamClickListener;
    }


//----------------------------施工队popudata---------------------------------------------------------------


//----------------------------改造类型popudata---------------------------------------------------------------

    private List<AddNewBuildTypeEntity> addnewtypelist = new ArrayList<>();
    private int buildtypeIndex = 0;
    private List<String> beanTypeList = new ArrayList<>();
    private List<String> beanTypeIDList = new ArrayList<>();

    private void setbuildTypePopuData(View view, final ListPopupWindow mPopupWindow, final List<AddNewBuildTypeEntity> datalist) {

//        addnewtypelist.clear();
//        for (AddNewBuildTypeEntity abte : datalist) {
//            addnewtypelist.add(abte);
//        }

        myBuildTypeAdapter = new GaizaoTypeAdapter(_mActivity, datalist);
        mPopupWindow.setAdapter(myBuildTypeAdapter);

        //弹出的位置  弹出锚点
        mPopupWindow.setAnchorView(view);

        mPopupWindow.setVerticalOffset(ConvertUtils.dp2px(_mActivity, 16));


        //设置宽高
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);

        mPopupWindow.setModal(true);//设置模态框，设置为true响应物理键

        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

                for (AddNewBuildTypeEntity rb : addnewtypelist) {
                    beanTypeList.add(rb.getText());
                    beanTypeIDList.add(rb.getValue());
                }


                String buildtype_n = removeRepeat(beanTypeList).toString();
                if(buildtype_n.contains("[")){
                    buildtype_n= StringUtil.deleteCharString(buildtype_n,'[');
                }
                if(buildtype_n.contains("]")){
                    buildtype_n= StringUtil.deleteCharString(buildtype_n,']');
                }
                if(buildtype_n.contains(" ")){
                    buildtype_n=StringUtil.deleteCharString(buildtype_n,' ');
                }


                String beanType_id = removeRepeat(beanTypeIDList).toString();
                if(beanType_id.contains("[")){
                    beanType_id=StringUtil.deleteCharString(beanType_id,'[');
                }
                if(beanType_id.contains("]")){
                    beanType_id=StringUtil.deleteCharString(beanType_id,']');
                }
                if(beanType_id.contains(" ")){
                    beanType_id=StringUtil.deleteCharString(beanType_id,' ');
                }

                if(TextUtils.isEmpty(addNewTvBuildtype.getText().toString().trim())){

                    addnewentity.setGaizao_type_n("");
                    addnewentity.setGaizao_type("");
                }

//                addnewentity.setGaizao_type_n(buildtype_n);
//                addnewentity.setGaizao_type(beanType_id);


                Log.i("改造类型显示", "内容: " + addnewentity.getGaizao_type_n());
                Log.i("改造类型显示", "ID: " + addnewentity.getGaizao_type());


                beanTypeList.clear();
                beanTypeIDList.clear();
            }
        });



        //设置条目点击事件
        mPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //使用回调,显示数据

                if (datalist.get(position).isSelected() == false) {
                    buildtypeIndex++;
                    addnewtypelist.add(datalist.get(position));
                    datalist.get(position).setSelected(true);
                } else {
                    buildtypeIndex--;
                    if (addnewtypelist.contains(datalist.get(position))) {
                        addnewtypelist.remove(datalist.get(position));
                    }
                    datalist.get(position).setSelected(false);
                }
                if (buildtypeIndex == 0) {
                    addNewTvBuildtype.setText("");
                    addnewtypelist.clear();
                    mPopupWindow.dismiss();
                } else {
                    //使用回调,显示数据
                    if (buildTypePopuListener != null) {
                        buildTypePopuListener.show(addnewtypelist);
                    }
                }

                myBuildTypeAdapter.notifyDataSetChanged();
            }
        });
        mPopupWindow.show();
    }

//    public AddNewBuildTypePopuListener anbtbtClickListener;
//
//    public void setbuildTypePopuClickListener(AddNewBuildTypePopuListener popudefaultClickListener) {
//        this.anbtbtClickListener = popudefaultClickListener;
//    }
    public BuildTypePopuListener buildTypePopuListener;

    public void setbuildTypePopuClickListener(BuildTypePopuListener buildTypePopuListener) {
        this.buildTypePopuListener = buildTypePopuListener;
    }
//----------------------------改造类型popudata----------------------------------------------------

//------------------------县乡村setdefaultPopuData-------------------------------------------------

    /**
     * 显示listpopuwindow,并使用回调,显示数据
     *
     * @param view
     * @param mPopupWindow
     * @param datalist
     */
    private void setdefaultPopuData(View view, final ListPopupWindow mPopupWindow, final List<String> datalist) {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(_mActivity, android.R.layout.simple_list_item_1, datalist);
        mPopupWindow.setAdapter(adapter);

        //弹出的位置  弹出锚点
        mPopupWindow.setAnchorView(view);
        //设置宽高
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);

        mPopupWindow.setModal(true);//设置模态框，设置为true响应物理键
        //设置条目点击事件
        mPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //使用回调,显示数据
                if (popudefaultClickListener != null) {
                    popudefaultClickListener.show("" + datalist.get(position));
                }
                mPopupWindow.dismiss();
            }
        });
        mPopupWindow.show();
    }

    public PopuClickListener popudefaultClickListener;

    public void setdefaultPopuClickListener(PopuClickListener popudefaultClickListener) {
        this.popudefaultClickListener = popudefaultClickListener;
    }
//--------------------------------------------------------------------------------------


//====================listpopuwindow  县 村=======================================

    /**
     * 显示listpopuwindow,并使用回调,显示数据
     *
     * @param view
     * @param mPopupWindow
     * @param datalist
     */

    private void setPopuData(View view, final ListPopupWindow mPopupWindow, final List<CountyEntity> datalist) {

        try{


            //清空集合,添加数据
            namelist.clear();
            for (CountyEntity ce : datalist) {
                namelist.add(ce.getText());
            }
            ArrayAdapter<String> adapter = new ArrayAdapter<>(_mActivity, android.R.layout.simple_list_item_1, namelist);
            mPopupWindow.setAdapter(adapter);

            //弹出的位置  弹出锚点
            //mPopupWindow.setAnchorView(view);
            mPopupWindow.setAnchorView(addNewAcceptanceAddress);

            mPopupWindow.setVerticalOffset(ConvertUtils.dp2px(_mActivity, 9));

            //设置宽高
            mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            mPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);

            mPopupWindow.setModal(true);//设置模态框，设置为true响应物理键
            //设置条目点击事件
            mPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //使用回调,显示数据
                    if (popuClickListener != null) {
                        popuClickListener.show(datalist.get(position), datalist.get(position).getText());
                    }
                    mPopupWindow.dismiss();
                }
            });
            mPopupWindow.show();

        }catch (Exception e){

        }
    }

    public ContyPopuListener popuClickListener;

    public void setPopuClickListener(ContyPopuListener popuClickListener) {
        this.popuClickListener = popuClickListener;
    }
//--------------------------------------------------------------------------------------


//=======================上传图片=====================================================

    /**
     * 点击添加图片,并同时是上传图片选择
     */
    private void showPhotoPic() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            if (ContextCompat.checkSelfPermission(_mActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                    != PackageManager.PERMISSION_GRANTED) {//  如果没有申请权限
//                if (ActivityCompat.shouldShowRequestPermissionRationale(_mActivity, Manifest.permission.CAMERA)) {
//                    ToastUtils.showShortToast(_mActivity, "您已经拒绝过一次");
//                }
//                //申请phone WRITE_EXTERNAL_STORAGE权限
//                ActivityCompat.requestPermissions(_mActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
//                        REQUEST_CODE_SOME_FEATURES_PERMISSIONS);
//
//            } else {
//                Intent intent = new Intent();
//                intent.addCategory(Intent.CATEGORY_OPENABLE);
//                intent.setType("image/*");
//                if (Build.VERSION.SDK_INT < 19) {
//                    intent.setAction(Intent.ACTION_GET_CONTENT);
//                } else {
//                    intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
//                }
//                this.startActivityForResult(intent, PhotoPicker.REQUEST_CODE);
////                // 如果申请了权限 则直接进入相册
////                showPhotoPicker();
//            }
//
//        } else {
//            // 版本小于6.0
//            showPhotoPicker();
//        }

        showPhotoPicker();
    }

    /**
     * 显示图片选择
     * <p>
     * 要改图片框架了
     */
    private void showPhotoPicker() {
//        打开文件管理器
//        PhotoPicker.builder()
//                .setPhotoCount(1) //显示图片张
//                .setShowCamera(false) //是否显示相机
//                .setShowGif(true)
//                .setPreviewEnabled(false)
//                .start(_mActivity, this, PhotoPicker.REQUEST_CODE);
        PhotoPicker.builder()
                .setPhotoCount(1) //显示图片张
                .setPreviewEnabled(false)
                .start(_mActivity, this, PhotoPicker.REQUEST_CODE);


    }


    /**
     * 获取图库返回的图片
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_CANCELED) {
            return;
        }
//        //返回图片
//        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE && data != null) {
////
//            LogUtils.e("显示", "onActivityResult");
//
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                Uri uri = data.getData();
//                LogUtils.e("uri", uri.toString());
//                String selectedImagePath = MyFileUtils.getPath(getActivity(), uri);
//                if (selectedImagePath != null) {
//                    mCurrentPhotoFile = new File(selectedImagePath);
//                    showLoadingDialog("正在上传图片");
//                    compressWithRx(mCurrentPhotoFile);
//                    LogUtils.e("selectedImagePath", selectedImagePath);
//                }
//            } else {
//                ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
//
//                showLoadingDialog("正在上传图片");
//                for (int i = 0; i < photos.size(); i++) {
//                    String uri = Uri.decode(photos.get(i));
//                    LogUtils.e("uri", uri);
//                    compressWithRx(new File(uri));
//                }
//            }
//
//        }

//        if (resultCode == RESULT_OK &&
//                (requestCode == PhotoPicker.REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) {
//
//            List<String> photos = null;
//            if (data != null) {
//                photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
//                Log.i("获取的图片", "onActivityResult: " + photos.get(0));
//            }
//        }

        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE && data != null) {
            LogUtils.e("显示", "onActivityResult");

            ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);

            //=========添加水印=========
            String absolutePath = photos.get(0);
            if(absolutePath.endsWith(":abc")&&mLayoutType!=4){
                absolutePath=absolutePath.substring(0,absolutePath.length()-4);
                savePic(absolutePath);
            }
            //==========添加水印========
            showLoadingDialog("正在上传图片");
            for (int i = 0; i < photos.size(); i++) {
                String uri = Uri.decode(photos.get(i));
                if(uri.endsWith(":abc")){
                    uri=uri.substring(0,uri.length()-4);
                }
                LogUtils.e("uri", uri);
                try {
                    compressWithRx(new File(uri));
                } catch (Exception e) {
                    Toast.makeText(_mActivity, "请重新上传", Toast.LENGTH_SHORT).show();

                }
            }

        }
    }

    private void savePic(String filename) {

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPurgeable = true;
        options.inSampleSize = 2;
        Bitmap bm= BitmapFactory.decodeFile(filename,options);


        File file = new File(filename);

        try {
            FileOutputStream fos = new FileOutputStream(file);
            String time =netTime;
            String address = MyApplication.getAddress();
            if(address==null){
                address="";
            }
            String content=time+";"+address;
            Bitmap newbm = ImageUtils.drawTextToRightBottom(_mActivity, bm, content,
                    25, ContextCompat.getColor(_mActivity,R.color.show2), 10, 10);
            newbm.compress(Bitmap.CompressFormat.JPEG, 100, fos);// 把数据写入文件
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 压缩单张图片 RxJava 方式
     */
    private void compressWithRx(File file) throws Exception {

        Flowable.just(file)
                .observeOn(Schedulers.io())
                .map(new Function<File, File>() {
                    @Override
                    public File apply(@NonNull File file) {//  throws Exception
                        try {
                            File file1 = Luban.with(_mActivity).load(file).get();
                            return file1;
                        } catch (Exception e) {
                            //对于文件损坏的文件/压缩失败的文件,也能上传,但是,在主线程中提示
                            //记住,修改权限
                            _mActivity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    //Toast.makeText(_mActivity, "请重新上传", Toast.LENGTH_SHORT).show();
                                    showShortToast("请重新上传");
                                }
                            });

                            return file;
                        }
                        //return Luban.with(_mActivity).load(file).get();

                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<File>() {
                    @Override
                    public void accept(@NonNull File file) {
                        LogUtils.e("fileinfo", "file- " + file.length() / 1024 + "k" + " name- " + file.getName() + " paht- " + file.getPath());
                        //上传图片
                        if (file == null) {
                            Toast.makeText(_mActivity, "请重新上传", Toast.LENGTH_SHORT).show();
                        } else {
                            uploadImgFile(file, file.getName(), file.getPath());
                        }

                    }


                });


    }


    /**
     * 上传单张图片
     *
     * @param file
     * @param fileName
     */
    private void uploadImgFile(final File file, final String fileName, final String filepath) {
        //uploadFile
        //http://192.168.70.188:8080/rest/adj/upload
        //String url="http://192.168.70.188:8080/rest/adj/upload";
        String url = HttpApis.upload_image;

        Map<String,String> params = new HashMap<>();
        String location_str = MyApplication.getAddress();
        if(location_str!=null&&location_str.contains(";")){
            String[] split = location_str.split(";");
            if(split[0]!=null){
                params.put("address",split[0]);
            }
            if(split[1]!=null){
                params.put("lw",split[1]);
            }
        }
        params.put("token",token_data);
        HttpUtils.requestPostFileUploadesLocation(getActivity(), url, fileName, file,params, new Request() {
            @Override
            public void success(String jsonStr) {
                super.success(jsonStr);
                Log.i("上传图片成功", "jsonSuccess  " + jsonStr + "~~~" + fileName);
                UploadImageEntity uploadImageEntity = GsonTools.changeGsonToBean(jsonStr, UploadImageEntity.class);
                if ("SUCCESS".equals(uploadImageEntity.getState())) {

                    if(mLayoutType==4){//身份证
                        uploadImageEntity.setIsrepeat("0");
                    }

                    if(imageName.contains(uploadImageEntity.getPicmd5code())){
                        showAlertOnlyPos(_mActivity,"图片上传","图片上传重复,请重新上传");
                        isUploadSuccess = false;

                    }else{
                        imageName.add(uploadImageEntity.getPicmd5code());
                        if("0".equals(uploadImageEntity.getIsrepeat())){//0表示不重复  1表示重复
                            isUploadSuccess = true;
                            displayUploadImgFile(uploadImageEntity, fileName);  //将img显示
                        }else {
                            //showShortToast("图片上传重复,请重新上传");
                            showAlertOnlyPos(_mActivity,"图片上传","图片上传重复,请重新上传");
                            isUploadSuccess = false;
                        }
                    }



                    //isUploadSuccess = true;
                    // annewImageList.add(uploadImageEntity.g);
                    //uploadFileCustomEntity = new UploadFileCustomEntity(uploadImageEntity.getUrl(), filepath, uploadImageEntity.getSize(), uploadImageEntity.getType());
                    //displayUploadImgFile(uploadImageEntity, fileName);  //将img显示

                } else {
                    //showShortToast("上传失败，图片大小不能超过4兆");
                    showAlertOnlyPos(_mActivity,"图片上传","，上传失败，图片大小不能超过4兆");
                    isUploadSuccess = false;
                }

                cancelLoadingDialog();
            }

            @Override
            public void error(String error) {
                super.error(error);
                isUploadSuccess = false;
                cancelLoadingDialog();
            }
        });

    }

    private int mLayoutType = -1;

    private void displayUploadImgFile(UploadImageEntity uploadImageEntity, String fileName) {
        switch (mLayoutType) {
            case 1:

                sellIvMyFileThree.setVisibility(View.GONE);
                image_show_B.setVisibility(View.VISIBLE);
                // LogUtils.e("上传图片成功", "展示图片 1 " + uploadFileCustomEntity.filepath);
                Glide.with(_mActivity).load(uploadImageEntity.getFilePath())
//                        .diskCacheStrategy(DiskCacheStrategy.ALL)
//                        .centerCrop()
                        .into(image_show_B);


                before_ima[0] = uploadImageEntity.getFileID();
                before_ima[1] = uploadImageEntity.getFilePath();
                before_ima[2] = "13";//adjunct_type : 据上传图片定
                before_ima[3] = uploadImageEntity.getFileExt();
                before_ima[4] = uploadImageEntity.getSize();
                before_ima[5] = "改造前";//file_des:据上传图片定 身份证正面\大门照
                before_ima[6] = fileName;
                before_ima[7] = uploadImageEntity.getPicmd5code();

                showArray(before_ima);


                if (isUploadSuccess) {
                    isImageBfSuccess = isUploadSuccess;
                }
                break;
            case 2:

                sellIvMyFileFour.setVisibility(View.GONE);
                image_show_M.setVisibility(View.VISIBLE);
                //LogUtils.e("上传图片成功", "展示图片 2 " + uploadFileCustomEntity.filepath);
                Glide.with(_mActivity).load(uploadImageEntity.getFilePath()).into(image_show_M);

                ing_ima[0] = uploadImageEntity.getFileID();
                ing_ima[1] = uploadImageEntity.getFilePath();
                ing_ima[2] = "1401";//adjunct_type : 据上传图片定
                ing_ima[3] = uploadImageEntity.getFileExt();
                ing_ima[4] = uploadImageEntity.getSize();
                ing_ima[5] = "改造中";//file_des:据上传图片定 身份证正面\大门照
                ing_ima[6] = fileName;
                ing_ima[7] = uploadImageEntity.getPicmd5code();


                if (isUploadSuccess) {
                    isImageMidSuccess = isUploadSuccess;
                }
                break;
            case 3:
                sellIvMyFileFive.setVisibility(View.GONE);
                image_show_F.setVisibility(View.VISIBLE);
                Glide.with(_mActivity).load(uploadImageEntity.getFilePath()).into(image_show_F);

                after_ima[0] = uploadImageEntity.getFileID();
                after_ima[1] = uploadImageEntity.getFilePath();
                after_ima[2] = "15";//adjunct_type : 据上传图片定
                after_ima[3] = uploadImageEntity.getFileExt();
                after_ima[4] = uploadImageEntity.getSize();
                after_ima[5] = "改造后";//file_des:据上传图片定 身份证正面\大门照
                after_ima[6] = fileName;
                after_ima[7] = uploadImageEntity.getPicmd5code();

                if (isUploadSuccess) {
                    isImageAfSuccess = isUploadSuccess;
                }
                break;
            case 4:
                sellIvMyFileOne.setVisibility(View.GONE);
                image_show_ID.setVisibility(View.VISIBLE);
                Glide.with(_mActivity).load(uploadImageEntity.getFilePath()).into(image_show_ID);


                idcard_ima[0] = uploadImageEntity.getFileID();
                idcard_ima[1] = uploadImageEntity.getFilePath();
                idcard_ima[2] = "11";//adjunct_type : 据上传图片定
                idcard_ima[3] = uploadImageEntity.getFileExt();
                idcard_ima[4] = uploadImageEntity.getSize();
                idcard_ima[5] = "身份证";//file_des:据上传图片定 身份证正面\大门照
                idcard_ima[6] = fileName;
                idcard_ima[7] = uploadImageEntity.getPicmd5code();


                if (isUploadSuccess) {
                    isImageIdSuccess = isUploadSuccess;
                }
                break;
            case 5:
                sellIvMyFileTwo.setVisibility(View.GONE);
                image_show_D.setVisibility(View.VISIBLE);
                Glide.with(_mActivity).load(uploadImageEntity.getFilePath()).into(image_show_D);

                fodoor_ima[0] = uploadImageEntity.getFileID();
                fodoor_ima[1] = uploadImageEntity.getFilePath();
                fodoor_ima[2] = "12";//adjunct_type : 据上传图片定
                fodoor_ima[3] = uploadImageEntity.getFileExt();
                fodoor_ima[4] = uploadImageEntity.getSize();
                fodoor_ima[5] = "大门照";//file_des:据上传图片定 身份证正面\大门照
                fodoor_ima[6] = fileName;
                fodoor_ima[7] = uploadImageEntity.getPicmd5code();


                if (isUploadSuccess) {
                    isImageDoorFontSuccess = isUploadSuccess;
                }

                break;

            case 6:
                sellIvGaizaozhongtwo.setVisibility(View.GONE);
                imageGaizaozhongtwo.setVisibility(View.VISIBLE);
                Glide.with(_mActivity).load(uploadImageEntity.getFilePath()).into(imageGaizaozhongtwo);

                ing_two_ima[0] = uploadImageEntity.getFileID();
                ing_two_ima[1] = uploadImageEntity.getFilePath();
                ing_two_ima[2] = "1402";//adjunct_type : 据上传图片定
                ing_two_ima[3] = uploadImageEntity.getFileExt();
                ing_two_ima[4] = uploadImageEntity.getSize();
                ing_two_ima[5] = "补充照片1";//file_des:据上传图片定 身份证正面\大门照
                ing_two_ima[6] = fileName;
                ing_two_ima[7] = uploadImageEntity.getPicmd5code();

                if(isUploadSuccess){
                    isImageMidTwoSuccess=isUploadSuccess;
                }

                break;

            case 7:
                sellIvGaizaozhongthree.setVisibility(View.GONE);
                imageGaizaozhongthree.setVisibility(View.VISIBLE);
                Glide.with(_mActivity).load(uploadImageEntity.getFilePath()).into(imageGaizaozhongthree);

                ing_three_ima[0] = uploadImageEntity.getFileID();
                ing_three_ima[1] = uploadImageEntity.getFilePath();
                ing_three_ima[2] = "1403";//adjunct_type : 据上传图片定
                ing_three_ima[3] = uploadImageEntity.getFileExt();
                ing_three_ima[4] = uploadImageEntity.getSize();
                ing_three_ima[5] = "补充照片2";//file_des:据上传图片定 身份证正面\大门照
                ing_three_ima[6] = fileName;
                ing_three_ima[7] = uploadImageEntity.getPicmd5code();

                if(isUploadSuccess){
                    isImageMidThreeSuccess=isUploadSuccess;
                }

                break;
            default:
                break;

        }

    }

    private void showArray(String[] arr) {
        for (String str : arr) {
            Log.i("数组数据", "showArray: " + str);
        }
    }


    //=====================申请权限============================================================
    private static final int REQUEST_CODE_SOME_FEATURES_PERMISSIONS = 111;
    private boolean isShowDialog = true;

    /**
     * 申请权限
     */
    private void showPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(_mActivity, Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {//  如果没有申请权限
                //申请phone WRITE_EXTERNAL_STORAGE权限
                ActivityCompat.requestPermissions(_mActivity,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.CAMERA},
                        REQUEST_CODE_SOME_FEATURES_PERMISSIONS);
            }
        }
    }

    /**
     * 权限回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case REQUEST_CODE_SOME_FEATURES_PERMISSIONS: {
                System.out.println("Permissions --> " + permissions.length);
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        System.out.println("Permissions --> " + "Permission Granted: " + permissions[i]);
                    } else if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                        System.out.println("Permissions     --> " + "Permission Denied: " + permissions[i]);
                        if (isShowDialog) {
                            isShowDialog = false;
                            showPermissionDialog();
                        }

                    }
                }
            }
            break;
            default: {
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }

    }

    /**
     * 显示权限对话框
     */
    private void showPermissionDialog() {
        showAlertDialog(_mActivity, "权限申请", "为了您可以上传图片请打开此权限,点确认再次申请", new DialogClick() {
            @Override
            public void PositiveMessage() {
                showPermission();
            }

            @Override
            public void NegativeMessage() {
                showShortToast("您将无法上传图片信息");
                isShowDialog = true;
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (addnewentity != null) {
            addnewentity = null;
        }
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
        OkHttpUtils.getInstance().cancelTag(this);
        cancelLoadingDialog();

    }
}
